图片做一个单独的
//上传图片,返回attach_id
@RequestMapping(value = "/addImg")
public BaseResponse addImg(HttpServletRequest request, @RequestParam("file") MultipartFile file, String flag) throws UnsupportedEncodingException {
request.setCharacterEncoding("utf-8");
BaseResponse msg = new BaseResponse();
//做文件上传
if ("".equals(file.getName()) || file.isEmpty()) {
new BizException(ErrorCode.WRONG_FILE_FULL.getDesc());
}
if (file.getSize() > 3000000) {
new BizException(ErrorCode.WRONG_FILE_UPLOAD_PASS.getDesc());
}
//附件对象
Attach attach = new Attach();
String path = uploadPath + File.separator;
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
long attach_id = Long.valueOf(0);
//判断文件
if (!file.isEmpty()) {
//上传的文件的名称
String oldFileName = file.getOriginalFilename();
attach.setName(oldFileName.substring(0, oldFileName.lastIndexOf(".")));
//取文件名的后缀
String suffix = oldFileName.substring(oldFileName.lastIndexOf("."));
//判断文件格式和类型 GIF,PNG 或JPG
if (".jpg".equalsIgnoreCase(suffix)) {
attach.setType("jpg");
} else if (".png".equalsIgnoreCase(suffix)) {
attach.setType("png");
} else if (".gif".equalsIgnoreCase(suffix)) {
attach.setType("gif");
} else if (".doc".equalsIgnoreCase(suffix)) {
attach.setType("doc");
} else if (".word".equalsIgnoreCase(suffix)) {
attach.setType("word");
} else if (".pdf".equalsIgnoreCase(suffix)) {
attach.setType("pdf");
} else if (".docx".equalsIgnoreCase(suffix)) {
attach.setType("docx");
} else {
new BizException(ErrorCode.WRONG_FILE_UPLOAD_FORMAT.getDesc());
}
Long id = Utils.nextId();
//新的文件名
String fileName = id + suffix;
path = path + fileName;
attach.setAddress(path);
attach.setFlag(flag);
attach.setTime(Utils.getDate());
//文件保存路径
File savePath = new File(path);
//设置附件路径
try {
attach_id = attachService.addAttach(attach);
//通过封装好的方法将文件上传到指定的文件夹
file.transferTo(savePath);
} catch (IOException e) {
new BizException(ErrorCode.WRONG_FILE_UPLOAD.getDesc());
}
}
msg.setData(attach_id);
msg.setSuccess(true);
return msg;
}