前台代码:
html代码:
<div style="position: relative">
<button type="button" style="margin-left: 10px;" class="btn btn-primary" data-toggle="modal"> <i class="fa fa-plus"></i> 上传图片
</button>
<form id="imgForm">
<input type="file" id="uploadProductImg" class="EditImg"
style="bottom: 0;position: absolute;left: 100px;opacity: 0;margin-left: -60px;height: 50px;width: 140px;" name="file"/>
</form>
</div>
js代码
//图片上传
$("#uploadProductImg").on("change", function () {
var v = this.value;
if (!v) return;
var sz = this.files[0].size / 1024 / 1024;
var n = v.substring(v.lastIndexOf('.')).toLowerCase();
//不能大于5M
if (sz > 5) {
alert("图片大小不能超过5MB!");
return;
}
if (n == '.jpg' || n == '.jpeg' || n == '.png') {
//如果格式正确,上传图片过程中页面按钮不可点击
var formData = new FormData(document.getElementById("imgForm"));
$.ajax({
type: "POST",
url: constant.url.sc_platform.imgSubmit,
enctype: "multipart/form-data",
contentType: false,
processData: false,
cache: false,
data: formData,
success: function (result) {
$.modal.alertSuccess('上传成功');
var imgUrl = constant.url.sc_platform.tool.getResourceUrl(result.data.relatPath);
console.log('======'+imgUrl);
},
error: function (err) {
alert("图片上传失败!");
}
});
} else {
alert("您选择的文件类型只能是图片(jpg、jpeg或png)");
}
});
common.js
imgSubmit: basePlatform + "/api/v1/product/sampling/temp/imgSubmit",//上传图片
tool: {
//解析URL
getQueryString: function (name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]);
return null;
},
getResourceUrl: function (filePath) {
//获取图片的全路径,兼容旧版路径和新版路径
if (!filePath) {
return filePath;
}
if (filePath.indexOf("group1/M00") >= 0) {
//fastdfs路径
return JNHC_RESOURCE_PATH + "/" + filePath;
}
return JNHCpath + "/img/" + filePath;
}
},
后台代码:
controller:
@Value("${imageBaseUrl}")
String imageBaseUrl;
@PostMapping("/imgSubmit")
public Result imgSubmit(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) throws Exception {
String contentType = file.getContentType();//类型
String fileName = file.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
//String newName = "jcbg" + "." + suffix;
String newName = "jcbg.png";
String filePath = imageBaseUrl;
Map<String, String> map = new HashMap<>();
try {
uploadFile(file.getBytes(), filePath, newName);
map.put("imgName", newName);
map.put("realPath", newName);
} catch (Exception e) {
// TODO: handle exception
}
return ResultGenerator.genSuccessResult(map);
}
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath + fileName);
out.write(file);
out.flush();
out.close();
}
application设置储存路径
#服务器图片地址
imageBaseUrl = /home/Qd/FarmersPlatformFront/img/jcbgImg/
#本地测试
#imageBaseUrl = D:/AA/