Home > Software design >  upload only pdf and docx file with springboot
upload only pdf and docx file with springboot

Time:08-06

I have a method that upload files, i want to accept just (pdf) and (docx) files, how i can do that. this is the method :

@PostMapping("/upload")
public ResponseEntity<ResponseMessage> uploadFile (@RequestParam("file") MultipartFile file){
    String message = "";
    try {
        
      
        fileService.store(file);
  
      message = "Uploaded the file successfully: "   file.getOriginalFilename();
      return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
    } catch (Exception e) {
      message = "Could not upload the file: "   file.getOriginalFilename()   "!";
      return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(message));
    }
}

CodePudding user response:

You can set allowed content type for endpoint: @PostMapping("/upload", consumes = {MediaType.APPLICATION_PDF_VALUE, "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"})

Or you can validate file extension from input.

CodePudding user response:

Other solution is to validate file extension from input as suggested by @Kryszak. Simply add one if condition to allow pdf and docx. For Example :

if (StringUtils.endsWithIgnoreCase(fileName, "pdf") || StringUtils.endsWithIgnoreCase(fileName, "docx")){
 //process file
}
else{
 // show message to user, only accept pdf & docx files.
}
  • Related