There is a system. The frontend is written in react and the backend in java.
On the frontend part, there is an image (base64) and some fields (string) that need to be sent to the server.
'Content-Type': 'multipart/form-data'
I also know that on the backend, the image must have a MultipartFile type
I do not understand what format I need to convert the picture to.
Can you please advise me?
const formData = new FormData();
formData.append( 'image', store.image); // store.image - base64
formData.append( 'id-number-value', "id");
formData.append( 'id-number-type', "id_card");
fetch('/path', {
method: 'POST',
headers: { 'Content-Type': 'multipart/form-data' },
body: formData
} )
.then((response) => {
if (response.ok) {
resolve();
} else {
throw new Error(response.message);
}
})
.catch((error) => reject(error));
You can convert the base64 string to a blob first.
const formData = new FormData();
formData.append('id-number-value', "id");
formData.append('id-number-type', "id_card");
fetch(store.image)
.then(res => res.blob()).then(blob => {
formData.append('image', blob);
fetch('/path', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data'
},
body: formData
})
.then((response) => {
if (response.ok) {
resolve();
} else {
throw new Error(response.message);
}
})
.catch((error) => reject(error));
});
Related
fetch(base64)
.then(res => res.blob())
.then(blob => {
const file = new File([blob], 'Test name', { type: 'image/png' })
let formdata = new FormData()
formdata.append('file', file)
const request = axios.create({
baseURL: Config.API_HOST,
})
request.interceptors.request.use(configs => {
return {
...configs,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
}
})
console.log(file)
request
.post(UPLOAD_URL, formdata)
.then(res => console.log(res))
.catch(err => {
console.log(err)
})
})
With this code I am able to submit a base64 image to server but if I check that file on server, I see the file with correct name and type, except for the size is 0.
In the following snippet downloading works as expected but uploading is not working, getting a HTTP 500 response. The issue isn't backend as it works in Postman or equivalent.
What could be the issue?
return fetch('url', {
method: 'GET',
}).then((response) => {
//upload
if (response.status === 200) {
let blob = response.blob();
return fetch('url', {
method: 'POST',
headers: {
'Content-Type': 'application/octet-stream',
},
body: blob,
}).then((response) => {
console.log(response.status);
});
}
});
Try using form data,
if (response.status === 200) {
let blob = response.blob();
const formData = new FormData();
formData.set('file', blob);
return fetch('url', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data'
},
body: blob,
}).then((response) => {
console.log(response.status);
});
}
I was using axios to send form-data in RN but it's not working. Noww tried fetch every feild uploads except images. If i use postman, everything works fine.
here is my code:
const postOrder = () => {
var data = new FormData();
data.append('marca', marca);
data.append('modeo', modeo);
data.append('option', option);
data.append('descripcion', descripcion);
data.append('images[]', images);
data.append('userId', '2');
dispatch(saveOrder(data));
};
fetch(`${baseUrl}/save-order`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: data,
})
.then(res => res.json())
.then(json => {
// dispatch({type: 'ORDER', payload: response.data});
console.log('json1', json);
})
.catch(error => {
console.log(error);
});
every property/feild is beig uploaded except images. I have tried these methods also
data.append('file', {
uri: images,
type: 'image/jpeg',
name: 'images[]',
});
data.append('file',images,'images[])
Axios didn't worked for me but fetch api did. here's my working code:
Post function
const postOrder = () => {
var data = new FormData();
data.append('marca', marca);
data.append('modeo', modeo);
data.append('option', option);
data.append('description', description);
data.append('images[]', {
uri: images,
name: 'image.jpg',
type: 'image/jpeg',
});
data.append('userId', state.user.id);
dispatch(saveOrder(data));
};
Fetch api
fetch(`${baseUrl}/save-order`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: data,
})
.then(res => res.json())
.then(json => {
console.log('json1', json);
})
.catch(error => {
console.log(error);
});
if You want to send multiple file do this
images.forEach((item, i) => {
data.append('images[]', {
uri: item.path,
type: item.mime,
name: item.path.slice(-8, -1) + 'g',
});
});
const formData = new FormData();
formData.append('file', {
uri: pictureUri,
type: 'image/jpeg',
name: 'profile-picture'
})
I had the same issue, Adding type: 'image/jpeg', to the file attribute of the formData fixed it.
Here is my code
let formData = new FormData();
// Update the formData object
formData.append(
"myFile",
this.state.product_picture,
this.state.product_picture.name
);
var options = { content: formData };
const token = JSON.parse(localStorage.getItem('token'));
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
product_name:this.state.product_name,
product_description:this.state.product_description,
product_picture:formData,
category_name:this.state.category_choosen,
})
};
fetch('http://cms.test/api/products/insert_supplier_product?token='+token, requestOptions)
.then(response => response.json())
.then(data => {
this.setState({ product: data.product})
})
.catch(error =>{
console.log("Product creation error", error);
});
I have this fetch api its always giving a 422 response I think what is happening is that its not reading a file as I want to upload a file it all works in postman but when using react it crashes
The body here is the problem
inside the state there are some strings but inside the this.state.product_picture there is a file
Hope someone can help! Thank you!
SOLUTION: Using axios to call the api solved my problem
You cannot send a file in a JSON object in a request( atleast not without Base64 encoding it). Change your code in the following way to send a file with your form.
let formData = new FormData();
// Update the formData object
formData.append(
"myFile",
this.state.product_picture,
this.state.product_picture.name
);
formData.append("product_name",this.state.product_name);
formData.append("product_description",this.state.product_description);
formData.append("category_name",this.state.category_choosen);
var options = { content: formData };
const token = JSON.parse(localStorage.getItem('token'));
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData
};
fetch('http://cms.test/api/products/insert_supplier_product?token='+token, requestOptions)
.then(response => response.json())
.then(data => {
this.setState({ product: data.product})
})
.catch(error =>{
console.log("Product creation error", error);
});
I got an error every time when trying to POST data to the API.
Request:
changeUserAvatar(authParam, file) {
let formData = new FormData();
//file is actually new FileReader.readAsDataURL(myId.files[0]);
formData.append('profile_image', file);
fetch(BASE_URL + 'profile-image', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': authParam
},
body: formData
}).then((response) => {
return response.json();
}).then((response) => {
debugger;
}).catch((error) => {
console.error(error);
});
}
Error: profile_image can not be blank (422).
But it's not blank!
Request payload:
What do I do wrong?
Solved at GutHub: https://github.com/github/fetch/issues/505
I just had to leave Header without pointing any Content-Type manually.