I have a from where i upload files to my Spring API.
Controller:
@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;
}
Repository:
@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;
}
I would like to validate, that users can only upload certain file types (pdf/doc/docx...). How to do that in Spring?
You could just check a known list that you set:
private static final List<String> contentTypes = Arrays.asList("image/png", "image/jpeg", "image/gif");
And later in the code (where you want to validate) break off the file extension and check if it is in the list:
@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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With