![](/img/trans.png)
[英]Spring 3 MVC File Upload and Form Validation without losing the file
[英]Spring MVC File upload - Validation
我從那里將文件上傳到我的Spring API。
控制器:
@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 ...)。 春天怎么辦?
您可以只檢查設置的已知列表:
private static final List<String> contentTypes = Arrays.asList("image/png", "image/jpeg", "image/gif");
然后在代碼的后面(您要驗證的位置)斷開文件擴展名,並檢查它是否在列表中:
@Override
public boolean uploadCV(User user, MultipartFile file) {
String fileContentType = file.getContentType();
if(contentTypes.contains(fileContentType)) {
// You have the correct extension
// rest of your code here
} else {
// Handle error of not correct extension
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.