//添加图片
protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
FileItemFactory f = new DiskFileItemFactory();
ServletFileUpload su = new ServletFileUpload(f);
try{
List<FileItem> items = su.parseRequest(req);
Iterator<FileItem> car = items.iterator();
while(car.hasNext()){
FileItem item = car.next();
if(!item.isFormField()){
String fileName = item.getName();
ServletContext application = this.getServletContext();
String fExt = FilenameUtils.getExtension(fileName);
String path = application.getRealPath("/files");
String newName = UUID.randomUUID().toString().replace("-","")
+"."+fExt;
File file = new File(path,newName);
item.write(file);
Bokepic bokepic = new Bokepic();
bokepic.setSavepath("/files/"+newName);
bokepic.setRealpath(fileName);
bokepic.setCover(0);
BookService bs = new BookServiceImp1();
bs.addpic(bokepic);
String newPicId = bokepic.getId();
ETResponse response = new ETResponse();
response.setData(newPicId);
response.setMsg(ETEnums.SUCCESS.getMsg());
response.setCode(ETEnums.SUCCESS.getCode());
ETJSONUtils.writeObject(resp,response);
}
}
}catch(Exception e){
e.printStackTrace();
}
}
@PostMapping("/upload")
public Result<String> upload(MultipartFile file) throws Exception{
//获得源文件名称和后缀
String originalFilename = file.getOriginalFilename();
String suffix = FilenameUtils.getExtension(originalFilename);
//创建新的文件名称
String uuid = UUID.randomUUID().toString().replaceAll("-","");
String filename = String.format("%s%s%s",//占位符(占了三个参数),拼接三个参数
uuid,".",suffix);
//创建目标文件夹
File destDirectory = new File(destDir);
if(!destDirectory.exists()){
destDirectory.mkdirs();
}
//创建目标文件.并上传
File destFile = new File(destDirectory,filename);
file.transferTo(destFile);
String pic = "/pic/" + filename;//是为了之后拿图片的时候有个路径
log.info("pic path-{}" , pic);
return Result.success(pic);
}