1

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?

1 Answer 1

1

Finally managed to find the problem. My code is fine (you can use it as a sample for ultra-simple file upload tests...), however there was an XSS filter in the application, which changed the encoding to UTF-8. Removing this filter for multipart requests solved the problem.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.