我有一個從哪裏上傳文件到我的Spring API。Spring MVC文件上傳 - 驗證
控制器:
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public JSONObject handleCVUpload(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
User user=userService.findUserByAccessToken(new AccessTokenFromRequest().getAccessToken(request));
JSONObject messageJson = new JSONObject();
messageJson.put("success", userService.uploadCV(user, file));
return messageJson;
}
庫:
@Override
public boolean uploadCV(User user, MultipartFile file) {
boolean uploadsuccess = false;
String fileName = user.getUserId() + "_" + user.getName();
if (!file.isEmpty()) {
try {
String type = file.getOriginalFilename().split("\\.")[1];
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(new File("/data/" + fileName + "." + type)));
FileCopyUtils.copy(file.getInputStream(), stream);
stream.close();
uploadsuccess = true;
} catch (Exception e) {
System.err.println(e);
uploadsuccess = false;
}
}
return uploadsuccess;
}
我想驗證,用戶只能上傳特定類型的文件(PDF/DOC/DOCX ...)。 如何在Spring中做到這一點?
在'MultipartFile'實例上調用'getContentType'並查看它是什麼.. –
這是安全的嗎?你不能只是僞造一個ContentType? –
您可以使用Apache Tika查看文件的實際內容並查看它是否合法 –