How To Upload Files In Java Using Spring Boot Nginx

Posted By : Vipul Pandey | 11-Dec-2017

In this blog, I am focusing out a feature provided by spring named multipart to upload the files on server to upload the files add the following dependencies on your file.

import java.io.IOException;     // to handle exception
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.web.multipart.MultipartFile;     // to handle upload file
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

//controller handeling 
    @PostMapping(value = "/icon")
    public String handleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes) {
        String fileName = addIconInActivityType(file);
        redirectAttributes.addFlashAttribute("message",
                "You successfully uploaded " + fileName + "!");
        return "redirect:/";
    }

    public  String addIconInActivityType(MultipartFile file) throws IOException {
        byte[] bytes = file.getBytes();
        String modifiedFileName = System.currentTimeMillis() + file.getOriginalFilename().substring(file.getOriginalFilename().length() - 4);
        Path path = Paths.get("/opt/images/" + modifiedFileName);
        Files.write(path, bytes);

        return modifiedFileName;

    }
  

This will upload your file in opt/images folder having of currentMillies with the file name extension.Please be ensure to create the folder and verify the permissions.

 

Serving files via nginx 
Open default.conf of nginx which is located in etc/nginx/sites-enabled.default.conf
Add the following lines in your settings

location /images{
	alias "/opt/images";
}
  

Restart your nginx using command (in linux)

 sudo service nginx restart
  

To test the status

 sudo service nginx status
  

About Author

Author Image
Vipul Pandey

Vipul Pandey is a good team-player & developing application on MEAN and java spring boot. Vipul loves to keep rotating fingers in his keyboard until he creates somethings inspiring.Hobbies are playing cricket ,swimming & photography.

Request for Proposal

Name is required

Comment is required

Sending message..