react js fetch api using file upload not being sent to body - javascript

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);
});

Related

Convert base64 image to send as multipart/form-data

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));
});

Can't save state in React while POST API request

I have handleSubmit function that send two POST request, one for img upload and one for other information. I want to take the response from the img upload request and take the 'filename' and then store it in state so I can sent it with the other POST request.
Here is my Request Options
const postOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.serviceToken}`
},
body: JSON.stringify({
p_emp_id: empId,
p_pr_doc_type: docType,
p_from_date: fromDate,
p_to_date: toDate,
p_doc_number: docNumber,
p_addres: address,
p_addres_en: addressEN,
p_doc_store: docPath,
p_creator_id: creator,
p_org_id: org
})
};
Then here is my Handle Submit function
const handleSubmit = async (e) => {
e.preventDefault();
const data = new FormData();
data.append('file', selectedFiles);
await fetch(`${config.apiHost}single/`, {
method: 'POST',
body: data
})
.then((res) => res.json())
.then((img) => setDocPath(img.filename))
.catch((err) => {
console.log(err.message);
});
setEditOpen(false);
fetch(`${config.apiHost}api/employees/info/pr_docs/new/`, postOptions);
console.log(postOptions.body);
};
My state docPath stays empty while I'm trying to submit so after that I can't see it in my request.
you can refactor your code to this and lets see if it works;
let postOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.serviceToken}`
},
body: {
p_emp_id: empId,
p_pr_doc_type: docType,
p_from_date: fromDate,
p_to_date: toDate,
p_doc_number: docNumber,
p_addres: address,
p_addres_en: addressEN,
p_creator_id: creator,
p_org_id: org
}
};
for the handle submit it can be
const handleSubmit = async (e) => {
e.preventDefault();
const data = new FormData();
data.append('file', selectedFiles);
await fetch(`${config.apiHost}single/`, {
method: 'POST',
body: data
})
.then((res) => res.json())
.then((img) => {
const postOptionsBody = {...postOptions.body, p_doc_store : img.filename }
postOptions = {...postOptions, body : JSON.stringify(postOptionsBody) }
setDocPath(img.filename)
})
.catch((err) => {
console.log(err.message);
});
setEditOpen(false);
fetch(`${config.apiHost}api/employees/info/pr_docs/new/`, postOptions);
console.log(postOptions.body);
};

Generate body for multipart file upload using fetch in Javascript

I am trying to upload a file(uploadType=multipart) to Drive API V3 using fetch but the body is wrong as it is creating a file with the title unnamed.
var tmpFile=document.getElementById('inputFile').files;
tmpFile=tmpFile[0];
await fetch('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart', {
method: 'POST', // or 'PUT'
headers: {
'Authorization': 'Bearer '+accessToken,
},
body: {
metadata:{
'name':tmpFile.name,
'Content-Type':'application/json; charset=UTF-8'
},
media:{
'Content-Type': '*/*',
'name':tmpFile
}
}
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
Your metadata is not being properly uploaded if its uploading with a name of unnamed
const fs = require("fs");
const FormData = require("form-data");
const fetch = require("node-fetch");
const filePath = "./sample.txt";
const accessToken = "###";
token = req.body.token;
var formData = new FormData();
var fileMetadata = {
name: "sample.txt",
};
formData.append("metadata", JSON.stringify(fileMetadata), {
contentType: "application/json",
});
formData.append("data", fs.createReadStream(filePath), {
filename: "sample.txt",
contentType: "text/plain",
});
fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart", {
method: "POST",
body: formData,
headers: { Authorization: "Bearer " + accessToken },
})
.then((res) => res.json())
.then(console.log);
Uploading Files of multipart/form-data to Google Drive using Drive API with Node.js

send image array for fetch formData in react-native

With the console.log I can see the array imagenes and this is ok in proyect react-native, but on the server this variable does not arrive but if I get the array of dates and the variable description on the server
let body = new FormData();
body.append('descripcion', 'dsadsadsa');
body.append('fechas[]', '2018-05-05');
body.append('fechas[]', '2015-05-05');
const {page1, page2, page3, page4, page5} = this.props.items;
body.append('imagenes[]', { uri: page2[2], name:'photo1.jpg', type: 'image/jpg'});
body.append('imagenes[]', { uri: page2[3], name:'photo2.jpg', type: 'image/jpg'});
body.append('imagenes[]', { uri: page2[4], name:'photo3.jpg', type: 'image/jpg'});
fetch(url, {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body: body
})
.then(res => res.text())
.then(res => {
console.log(res)
}).catch((err) => {
console.log('err', err)
});
});
Thanks for help me!
the code upload data and file (images) in RN this is ok, the bug in vars size file php.ini (memory_limit, upload_max_filesize, post_max_size).
in nginx, edit file nginx.conf add or update command
client_max_body_size 500M
Link https://www.cyberciti.biz/faq/linux-unix-bsd-nginx-413-request-entity-too-large/

Error when POST file multipart/form-data (JavaScript)

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.

Categories