I'm trying to upload files to a Web server, using JQuery and Spring.
The web server is Tomcat.
This works well with text files, but not with binary files.
Uploading JPG or PDF, for example, produces larger files that cannot be opened.
I created a very simple web page just to demonstrate the problem:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
function upload() {
var post_data = new FormData();
post_data.append( 'file', $('input[type=file]')[0].files[0]);
$.ajax({
type: 'POST',
url: '/rest/api/events/',
cache: false,
data: post_data,
processData: false,
contentType: false
});
}
</script>
<body>
<input type="file" name="file" id="file">
<button id='uploadBtn' onclick='upload();'>Upload</button>
</body>
</html>
And the controller:
@RequestMapping(method = RequestMethod.POST, value = "/api/events")
@ResponseStatus(HttpStatus.OK)
public
@ResponseBody
Object addEvent(@RequestParam(value = "file", required = false) MultipartFile file) {
try {
file.transferTo(new File("C:\\" + file.getOriginalFilename()));
} catch (IllegalStateException | IOException e) {
}
return "";
}
Am I doing anything wrong?