SpringBoot图片上传(一)

简单描述:点击上传文件的图标,上传文件,上传成功后,图标编程上传的图片。

吐槽:文件上传下载这种东西,总是感觉莫名的虚-_-||  也不知道是造了什么孽,(其实就是IO File这一块的知识了解的不太深入)。

代码:

//html代码
<div class="col-md-6">
<label class="control-label flex" style="margin-top: 10px;">
上传图标<span class="star align-items">*</span>
</label>
<div class="">
<img th:src="@{/assets-new/apps/img/shangchuan.png}" id="imgPlanIcon"
width="35px" height="35px"/>
<input type="file" id="seledIcon" style="display:none"/>
</div>
<input type="hidden" name="planIcon" th:value="${plan?.planIcon}" id="planIcon"/>
</div>
//js代码
$("#imgPlanIcon").on("click", function () {
$("#seledIcon").trigger("click");
});
//此js要放到初始化下,否则中间的file不会被识别,checkFile()是否初始化都无所谓
$("#seledIcon").on("change", function () {
if ($('#seledIcon').val().length == 0) {
return;
}
// 前端判断选择的文件是否符合要求
if (!checkFile()) {
// 重置file input
$('#seledIcon').replaceWith($('#seledIcon').val('').clone(true));
return;
}
// 上传图片到项目临时目录下
var url = rootPath + "serv/plan/upLoadImage";
var icon = $('#seledIcon')[0].files[0];
var fd = new FormData();
fd.append('icon', icon);
$.ajax({
url: url,
type: "post",
//Form数据
data: fd,
cache: false,
async: false,
contentType: false,
processData: false,
success: function (data) {
if (data.result == "success") {
// 上传成功data为图片路径
var planIcon = data.fileName;
$('#planIcon').val(planIcon);
          //下边两行代码用于回显上传成功后的图标
var imgPlanIcon = rootPath + 'serv/plan/downLoadImage?planIcon=' + planIcon;
$('#imgPlanIcon').attr('src', imgPlanIcon);

        } else if (data.result == "fileIsEmpty") {
layer.msg("图片内容为空!");
} else if (data.result == "formatError") {
layer.msg("请检查图片格式是否为jpg!");
} else if (data.result == "sizeTooBig") {
layer.msg("图片大小超出512KB!");
} else if (data.result == "sizeError") {
layer.msg("图片尺寸必须为60*60!");
} else {
layer.msg("上传图片失败");
}
},
error: function () {
layer.msg("上传图片失败,后台系统故障");
}
});
// 重置file input
$('#seledIcon').replaceWith($('#seledIcon').val('').clone(true));
});
function checkFile() {
var maxsize = 512 * 1024;
var errMsg = "图片大小超出512KB!!!";
var browserCfg = {};
var ua = window.navigator.userAgent;
if (ua.indexOf("MSIE") >= 1) {
browserCfg.ie = true;
} else if (ua.indexOf("Firefox") >= 1) {
browserCfg.firefox = true;
} else if (ua.indexOf("Chrome") >= 1) {
browserCfg.chrome = true;
}
var obj_file = $('#seledIcon')[0];
var fileSize = 0;
var fileType;
if (browserCfg.firefox || browserCfg.chrome) {
fileSize = obj_file.files[0].size;
if (fileSize > maxsize) {
layer.msg(errMsg);
return false;
}
var fileName = obj_file.files[0].name;
fileType = fileName.slice(fileName.lastIndexOf(".") + 1).toLowerCase();
if (fileType != "jpg") {
layer.msg("请检查图片格式是否为jpg!");
return false;
}
} else if (browserCfg.ie) {
// ie浏览器,获取不到filesize,暂时通过前台验证,转到后台处理
} else {
// 其它类型的浏览器,暂时通过前台验证,转到后台处理
}
return true;
}
//后台java代码
//Controller中要声明路径
@Value("${constant.image_path}")
private String imagePath;

@Value("${constant.image_temp_path}")
private String imageTempPath;

@RequestMapping("/upLoadImage")
@ResponseBody
public Map<String, String> uploadFile(MultipartFile icon) throws Exception {
HashMap<String, String> map = new HashMap<>();
if (icon == null || icon.isEmpty()) {
map.put("result", "fileIsEmpty"); // 文件或内容为空
return map;
}
// 判断图片的格式是否符合要求
String fileName = icon.getOriginalFilename(); // 上传的文件名
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
if (!"jpg".equals(suffix)) {
map.put("result", "formatError"); // 文件格式错误
return map;
}
BufferedImage image = ImageIO.read(icon.getInputStream());
if (image == null) {
map.put("result", "formatError"); // 文件格式错误
return map;
}
// 判断图片的大小是否符合要求
Long iconSize = icon.getSize() / 1024;
if (iconSize > 512) {
map.put("result", "sizeTooBig"); // 图片超出指定大小
return map;
}

// 判断图片的尺寸是否符合要求
int width = image.getWidth();
int height = image.getHeight();
if (width != 60 || height != 60) {
map.put("result", "sizeError"); // 图片尺寸不合适
return map;
}

File dirPath = new File(imageTempPath);
// 判断文件夹是否存在
if (!dirPath.exists()) {
dirPath.mkdirs();
}
// 生成新的文件名称
String uuid = UuidUtil.get32UUID();
String newFileName = uuid + "." + suffix;
// 将上传文件保存到一个目标文件中
icon.transferTo(new File(imageTempPath + File.separator + newFileName));
map.put("result", "success");
map.put("fileName", newFileName);
return map;
} 
@RequestMapping("/downLoadImage")
public void downLoadFile(String planIcon, HttpServletResponse response) {
if (Tools.isEmpty(planIcon)) {
return;
}
File file = null;
file = new File(imagePath + File.separator + planIcon);
if (!file.exists()) {
file = new File(imageTempPath + File.separator + planIcon);
}

if (file.exists()) {
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(file));
out = new BufferedOutputStream(response.getOutputStream());
// 设置response内容的类型
response.setContentType(new MimetypesFileTypeMap().getContentType(file));
// 设置头部信息
response.setHeader("Content-disposition", "attachment;filename=" + planIcon);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

}
 

 

//constant.properties配置
# 上传图标的存放路径
constant.image_path=D:\\image\\icon
# 上传图标的临时存放路径
constant.image_temp_path=D:\\image\\temp

总结

posted @ 2018-10-19 16:13  ジ绯色月下ぎ  阅读(1146)  评论(0编辑  收藏  举报