Skip to content
Advertisement

Java: Image upload with JavaScript – File is damaged, corrupted or too large

I am using Spring Boot as backend server and I have a JavaScript frontend. For sending data between front- and backend I’m using the Axios library, which usually works pretty fine.

The Problem:
The image looks like this in the (Chrome) browser console: Console output It’s a very very long alphanumeric string and that’s what I send to the server with the following code:

JavaScript

I have no idea what the boundary thing does but it worked to receive a file in the backend tho…

On backend (spring) side I successfully receive an array of MultipartFiles:

JavaScript

I’ve also tried it file.transferTo(newFile); instead of in- and outputstreams – which didn’t work either.
After that I get the following output, which means that the image was saved successfully: /path/to/blob.jpg
If I check the path where the file was uploaded, there is a file named blob.jpg, but if I open it, the windows photo viewer has the following problem: Error in windows photo viewer I’ve opened the image before and after upload with notepad++:
Before upload: Image before upload (Byte Array) I think this is a byte array, but If I open the image after upload I get exactly the output of the browser. This means it didn’t get converted to a byte array (correct me if I’m wrong) and I believe that’s why it’s a corrupt image…

My questions are:

  • What’s the problem?
  • How can I fix it?

I really tried everything which crossed my mind but I ran out of ideas.

Thanks for your help! 🙂


I’ve read following *related* questions (but they **don’t** have an answer):
[Question1][5], [Question2][6], and **many** more…

Advertisement

Answer

I’ve finally found an answer on my own!

I think the problem was that I used the e.target.result (which is used to show the image on the frontend) but insted I had to use the JS File object. The standard HTML 5 file input fields return those File objects (as I’ve read here).

The only thing I had to do now is to make a FormData object, append the File Object, set the FormData as Body and set the Content-Type header and that’s it!

JavaScript

Those JS File Objects are recognized from Java as Multipart files:

JavaScript

I hope this is helpful 🙂

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement