上篇我们提到了多商品提交的小程序端,前端JS代码写完了现在我们来写后端代码.这里我的环境是JDK1.8+SpringBoot+Mybatis+MySql
,那么就解决图片上传和删除的代码.因为不涉及到数据入库的操作.订单保存我相信大家都没兴趣看.
@PostMapping("fileUpload")
public JsonResult fileUpload(@RequestParam("file") MultipartFile file){
try {
String fileName = file.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
if (!(suffixName.contains("jpg") || suffixName.contains("png"))) {
return JsonResult.successReuslt("不支持" + suffixName + "格式,请上传JPG或者PNG格式",null);
}
StringBuilder tempName = new StringBuilder();
tempName.append(DateUtil.dateToString(new Date(), DateUtil.data_now_time_format))
.append(UUID.randomUUID().toString().replace("-", "")).append(suffixName);
String newFileName = tempName.toString();
File fileDirectory = new File(WxConfig.FILE_PATH);
File destFile = new File(WxConfig.FILE_PATH + newFileName);
if (!fileDirectory.exists()) {
if (!fileDirectory.mkdir()) {
throw new IOException("文件夹创建失败,路径为:" + fileDirectory);
}
}
file.transferTo(destFile);
return JsonResult.successReuslt("成功",WxConfig.Http_Url + newFileName);
} catch (Exception e) {
e.printStackTrace();
return JsonResult.successReuslt("上传失败",null);
}
}
@GetMapping("deleteImg")
public JsonResult deleteImg (String imgPath) {
int lastIndexOf = imgPath.lastIndexOf("/");
String img_path = imgPath.substring(lastIndexOf + 1, imgPath.length());
img_path = WxConfig.FILE_PATH + img_path;
File file = new File(img_path);
if (file.exists()) {
if (file.delete()) {
return JsonResult.successReuslt("成功!", null);
} else {
return JsonResult.erroReuslt("失败");
}
} else {
return JsonResult.erroReuslt("失败");
}
}
WxConfig.FILE_PATH :这是图片服务器路径(静态资源映射)
WxConfig.Http_Url :这是我的图片路径前缀,如果是本地就是localhost.如果是线上就是域名