I am unable to send image and form data to mysql. My backend is in Java and when using postman it works fine. I am unable to do so when I send it from the frontend. I have input fields for username, title, description et al as well as the image. Please help where I am wrong.
Asked
Active
Viewed 440 times
0

JS11
- 21
- 5
2 Answers
0
The issue is, you are trying to send the file name which is wrong. You have to append the file like:
var file = event.target.files[0];
const formData = new FormData();
formData.append("file", file);
formData.append("var1", val1); // Other fields
await fetch("url", {
method: "POST",
body: formData
}).then({
// code here
}).catch({
// code here
});
And on the server side you will get the file in file
or whatever name you have provided at the time of appending it in the formdata.

Mayank Pandeyz
- 25,704
- 4
- 40
- 59
-
handleChange = (event) => { this.setState({ [event.target.name]: event.target.value }) } selectImageFile = (event) => { this.setState({ picture: event.target.files[0] }) } this is my event handler – JS11 Jul 09 '20 at 06:27
0
Please use this tricks
React: convert your media file to base64 string.
Java: convert base64 to image(img,pdf,xlxs,etc...)
Converting image to Base64(REACT.JS):
function convertBase64(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function () {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
convertBase64("path-of-the-image/user_picture.png", function (dataUrl) {
//console.log('RESULT:', dataUrl);
});
Converting Base64 to image(JAVA):
// Needed Imports
import java.io.ByteArrayInputStream;
import sun.misc.BASE64Decoder;
def sourceData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAgAEl...==';
// tokenize the data
def parts = sourceData.tokenize(",");
def imageString = parts[1];
// create a buffered image
BufferedImage image = null;
byte[] imageByte;
BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(imageString);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(bis);
bis.close();
// write the image to a file
File outputfile = new File("image.png");
ImageIO.write(image, "png", outputfile);

Talha Noyon
- 824
- 7
- 13