Skip to content

Instantly share code, notes, and snippets.

@KingSirLee
Created April 22, 2016 10:40
Show Gist options
  • Save KingSirLee/5d85e3b7a7c22c537cdf884ccc4541fb to your computer and use it in GitHub Desktop.
Save KingSirLee/5d85e3b7a7c22c537cdf884ccc4541fb to your computer and use it in GitHub Desktop.
SpringMVC multipart文件上传
@Controller
public class FileUploadController {
@Resource
private UploadManager uploadManager;
@RequestMapping(value = "", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
AttachmentDTO atta = new AttachmentDTO();
atta.setName(file.getOriginalFilename());
atta.setFileBytes(file.getBytes());
atta.setFileExt(FilenameUtils.getExtension(file.getOriginalFilename()));
return uploadManager.uploadFile(atta);
} else {
logger.warn("没有文件");
}
}
}
public class UploadManager{
public String uploadFile(AttachmentDTO atta){
Srting fileName = createFileName(); // 文件名
String dirPath = getDirPath(); // 获取文件存储路径
File d = new File(dirPath);
if (!d.exists()) {
d.mkdirs();
}
File destFilePath = new File(dirPath + fileName);
if (destFilePath.exists()) { //若文件已存在,则重新生成fileName保存
// 做处理
} else {
try {
FileCopyUtils.copy(atta.getFileBytes(), destFilePath);
} catch (IOException e) {
throw new BusinessException("附件存储失败,missionCode=" + missionCode, e);
}
}
return fileName;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment