spring boot实现文件上传
controller:
@RequestMapping(value = "/{id}/upload-change-type", method = POST)
@ResponseBody
public void uploadChangeFile(@PathVariable long id,MultipartHttpServletRequest req) {
try {
service.uploadChangeFile(id,req.getFile("changeFile").getInputStream(),req.getFile("changeFile").getOriginalFilename());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
service:
public void uploadChangeFile(long id, InputStream in,String fileName) throws IOException {
StatusChangeType sct = statusChangeTypeRepo.findById(id);
String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
File file = fileService.getFileOfChange(sct,suffix);
if(file.exists())
file.delete();
FileUtils.copyInputStreamToFile(in, file);
}
fileService.getFileOfChange(sct,suffix);
public File getFileOfChange(StatusChangeType sct,String suffix) {
File dir = FileUtils.
getFile(getTEMP_SUBDIR());
if(!dir.exists()) {
dir.mkdirs();
}
String fileName = sct.getId().toString()+"-"+sct.getMajor()+"-"+sct.getMinor()+"."+suffix;
File ret = new File(dir,fileName);
sct.setChangeFile(dir+"\\"+fileName);
statusChangeTypeRepo.save(sct);
return ret;
}