I am working on a jsp file upload using ajax call and I am able to hit the java controller in the HttpServletRequest I see the multipart file received but when I do request.getInputStream.readAllBytes(), I get an empty byte array
The ajax call in javascript
function saveFileUpload() {
var data = new FormData()
data.append("file", document.getElementById(fileName).files[0])
$.ajax({
type: 'POST',
data: data,
url: pageContext + "/upload",
processData: false,
contentType: false,
success: function(data) {},
error: function(e) {}
});
}
}
In Java controller
@RequestMapping(value = {"/upload"}, method = RequestMethod.POST)
public void fileUpload (
HttpServletRequest request, HttpServletResponse response){
byte[] arr = request.getInputStream().readAllBytes();
System.out.println(arr.length);
}
The above code prints arr.length as 0. Can someone tell me the reason for this issue?
I assume that you are using Springboot and your application supports multipart/form-data. After version 3.0 the Servlet API natively support it.
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void fileUpload(@RequestParam("file") MultipartFile file) throws IOException
{
if (!file.isEmpty())
{
byte[] bytes = file.getBytes();
// and so on
}
}
JQuery's Ajax:
function saveFileUpload() {
let data = new FormData()
data.append("file", document.getElementById(fileName).files[0])
$.ajax({
type: 'POST',
data: data,
url: pageContext + "/upload",
processData: false,
contentType: false,
success: function(data) {},
error: function(e) {}
});
}