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
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
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
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.