Introduction
In this article we are going to discuss about a logic to upload files into server with Spring Boot MVC application. We are going to store file name in a MYSQL data base server and file will be storing in a upload folder of application context.Html form to upload a file
To upload a file form must be of multipart encription type. we must add enctype="multipart/form-data" into form attribute.<form role="form" enctype="multipart/form-data" th:action="@{/addNewFile}" method="post" th:object="${rdata}" autocomplete="off"> . . . . <input type="file" name="myfile"/> </form>
Controller with handler method
Here we are going to learn with Spring Boot MVC based logic. Simply iam trying to share direct code of file upload handler method
@PostMapping("/addNewFile")
public void addNewFile(MultipartFile file,@ModelAttribute("rdata") Repositorydata rdata, BindingResult bindingResult,
HttpServletResponse response) throws DAOException, SQLException, IOException {
if (bindingResult.hasErrors()) {
// errors processing
}
if (!file.isEmpty()) {
// upload directory - change it to your own -- to create in eclipse --right click on project and go for folder option then give a name as upload
String UPLOAD_DIR = "upload";
// create a path from file name
Path path = Paths.get(UPLOAD_DIR);
// save the file to `UPLOAD_DIR`
// make sure you have permission to write
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
String fileName = String.valueOf(timestamp.getTime() + new Random().nextInt(1000));
fileName = fileName + "."+ file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
Files.copy(file.getInputStream(), path.resolve(fileName));// file.getOriginalFilename()));
}
}
Here we are checking whether file is selected or not to upload
In this line we have specified in which folder file is going to be stored
Downloading file
We need to write separate handler method to download uploaded file.
public Resource loadFileAsResource(String fileName) {
try {
String UPLOAD_DIR = "upload";
Path filePath = Path path = Paths.get(UPLOAD_DIR).toAbsolutePath().normalize();
Resource resource = new UrlResource(filePath.toUri());
if(resource.exists()) {
return resource;
} else {
throw new Exception("File not found " + fileName);
}
} catch (MalformedURLException ex) {
throw new MyFileNotFoundException("File not found " + fileName, ex);
}
}
@GetMapping("/downloadFile/{fileName:.+}")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request) throws IOException {
// Load file as Resource
Resource resource = fileStorageService.loadFileAsResource(fileName);
System.out.print(resource.getFile().getAbsolutePath());
// Try to determine file's content type
String contentType = null;
try {
contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
} catch (IOException ex) {
logger.info("Could not determine file type.");
}
// Fallback to the default content type if type could not be determined
if(contentType == null) {
contentType = "application/octet-stream";
}
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(contentType))
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
this is a method to get Resouce from a given file name
this is a end point to get file with the file name
in this line we are trying to get type of the file
Post a Comment
Post a Comment