Spring Boot file upload with Ajax
In this post is shown how to uploading a file (e.g. an image) using Ajax with a Spring Boot web application server side. JQuery will be used client-side to simplify our life.
Html form
The following is the minimal html form for file uploading:
<!-- Upload file form -->
<form id="upload-file-form">
<label for="upload-file-input">Upload your file:</label>
<input id="upload-file-input" type="file" name="uploadfile" accept="*" />
</form>
Javascript
With a javascript code we bind the on-change event for the input
element (that will be triggered when a file is chosen) and we send the file to the server with an Ajax POST using a FormData object.
// bind the on-change event
$(document).ready(function() {
$("#upload-file-input").on("change", uploadFile);
});
/**
* Upload the file sending it via Ajax at the Spring Boot server.
*/
function uploadFile() {
$.ajax({
url: "/uploadFile",
type: "POST",
data: new FormData($("#upload-file-form")[0]),
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
success: function () {
// Handle upload success
// ...
},
error: function () {
// Handle upload error
// ...
}
});
} // function uploadFile
Spring Boot controller
Server side we need a Spring Boot controller listening for an HTTP POST
at the url /uploadFile
. The controller’s method handle the uploaded file saving it locally in the filesystem.
/**
* POST /uploadFile -> receive and locally save a file.
*
* @param uploadfile The uploaded file as Multipart file parameter in the
* HTTP request. The RequestParam name must be the same of the attribute
* "name" in the input tag with type file.
*
* @return An http OK status in case of success, an http 4xx status in case
* of errors.
*/
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> uploadFile(
@RequestParam("uploadfile") MultipartFile uploadfile) {
try {
// Get the filename and build the local file path (be sure that the
// application have write permissions on such directory)
String filename = uploadfile.getOriginalFilename();
String directory = "/var/netgloo_blog/uploads";
String filepath = Paths.get(directory, filename).toString();
// Save the file locally
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(filepath)));
stream.write(uploadfile.getBytes());
stream.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(HttpStatus.OK);
} // method uploadFile
Some configurations
Spring Boot takes some optional configurations in order to limit file sizes. You can put them in the application.properties
file.
src/main/resources/application.properties
# Set the file size limit (default 1Mb). If you want to specify that files be
# unlimited set the multipart.maxFileSize property to -1.
multipart.maxFileSize = 3Mb
# Set the total request size for a multipart/form-data (default 10Mb)
multipart.maxRequestSize = 20Mb
Try yourself
You can try the above code getting it from our github repository:
https://github.com/netgloo/spring-boot-samples/tree/master/spring-boot-file-upload-with-ajax
References
https://spring.io/guides/gs/uploading-files/
http://hmkcode.com/spring-mvc-upload-file-ajax-jquery-formdata/
http://pauliusmatulionis.blogspot.it/2013/10/spring-mvc-ajax-file-upload.html
http://portfolio.planetjon.ca/2014/01/26/submit-file-input-via-ajax-jquery-easy-way/
-
Aravind Pilla
-
Andrea
-
-
Phumzile F Saleni
-
Andrea
-
-
Chawqi Hajar
-
Andrea
-
Chawqi Hajar
-
Andrea
-
Chawqi Hajar
-
David
-
Andrea
-
David
-
Kecci Kun
-
-
-
-
-
Aghil krishna
-
Andrea
-
Aghil krishna
-
Aghil krishna
-
Andrea
-
-
-
-
Jiten Shahi
-
Andrea
-
Jiten Shahi
-
Andrea
-
-
-
-
Abel abelique
-
Jakkarin
-
Andrea
-
-
Chandra Chandra
-
andretti1977
-
Andrea
-
-
Herculano Cunha
-
Andrea
-
-
wided ben abdallah
-
Andrea
-
wided ben abdallah
-
-
-
Dedy
-
Andrea
-
Dedy
-
-
-
Nicholas
-
Andrea
-
-
Waqas Rana
-
Andrea
-
-
David
-
Andrea
-
-
Deepa R