圖片做一個單獨的
//上傳圖片,返回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;
}