I am uploading file in react using axios.
when I am doing
alert(values.attachedFile[0]);
but when I am sending values.attachedFile[0] in axios post request enpty thing is going.
const { result } = await axios.post(app.resourceServerUrl + '/file/upload', {
data: values.attachedFile[0],
headers: {
'Content-Type': 'multipart/form-data',
},
});
but as part of request is is going empty.
what mistake I am doing?
To upload file with axios you need to use FormData:
const formData = new FormData();
// ...
formData.append("data", values.attachedFile[0]);
axios.post(app.resourceServerUrl + '/file/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
Related
I am trying to convert the below code which is using request module to axios module to send the POST request.
request module code:
const imageFile = fs.createReadStream('image.jpeg');
const imgName = "image" + ".jpeg";
var options = {
'method': 'POST',
'url': url,
'headers': {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
'Accept': 'application/json'
},
formData: {
'image': {
'value': imageFile,
'options': {
'filename': imgName,
'contentType': null
}
}
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log("SUCCESS");
});
The above code works fine and the image is posted successfully with the request module. But when I convert the same to axios, I am getting a 500 Error. (AxiosError: Request failed with status code 500)
axios module code:
const FormData = require('form-data')
const imageFile = fs.createReadStream('image.jpeg');
const imgName = "image" + ".jpeg";
const bodyFormData = new FormData();
bodyFormData.append("image['value']", imageFile);
bodyFormData.append("image['options']['filename']", imgName)
// bodyFormData.append("image['options']['contentType']", null)
console.log(bodyFormData)
const formHeaders = bodyFormData.getHeaders();
axios.post(url, bodyFormData, {
headers: {
...formHeaders,
'Cache-Control': 'no-cache',
'Accept': 'application/json',
}
}).then(function (response) {
console.log('SUCCESS');
}).catch(function (error) {
throw new Error(error);
});
Can anyone find out what I am doing wrong here?
Is there any other way to post the image using axios other than using form-data?
See the documentation for FormData#append(). You can provide extra data like the file name as the 3rd options parameter
const bodyFormData = new FormData();
// Pass filename as a string
bodyFormData.append("image", imageFile, imgName);
// or to specify more meta-data, pass an object
bodyFormData.append("image", imageFile, {
filename: imgName,
contentType: "image/jpeg",
});
axios.post(url, bodyFormData, {
headers: {
Accept: "application/json",
"Cache-Control": "no-cache",
...bodyFormData.getHeaders(),
},
});
Under the hood, request() does something very similar with the exact same form-data library. See request.js
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'm getting this error when trying to do a POST request using axios:
Error: Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream at createError
Here's my request:
async function fetchAndHandleErrors() {
const url = `/claim/${claimId}`;
const headers = {
Accept: 'application/json',
Authorization: `Bearer ${token}`,
};
const body = new FormData();
body.append('damage_description', damageDescription);
body.append('damaged_phone', {
uri: imageUri,
type: 'image/jpeg', // or photo.type
name: imageUri,
});
const result = await axios({
'post',
url: `${baseUrl}${url}`,
data: body,
headers,
});
return result.data;
}
I tried removing result.data and still get the same error. Why is that?
If you eventually still need a solution for this, I managed to get rid of this error by using the formData.pipe() method. For your case, it could look like this :
import axios from 'axios'
import concat from 'concat-stream'
import fs from 'fs'
import FormData from 'form-data'
async function fetchAndHandleErrors() {
const file = fs.createReadStream(imageUri)
let body = new FormData();
body.append('damage_description', damageDescription);
body.append('damaged_phone', file);
body.pipe(concat(data => {
const url = `/claim/${claimId}`;
const headers = {
'Authorization': `Bearer ${token}`,
...body.getHeaders()
};
const result = await axios({
'post',
url: `${baseUrl}${url}`,
data: body,
headers,
});
return result.data;
}))
}
Please let me know if you still encounters your issue, I'll be glad to help !
I was trying to upload file in react, but failed because there was bad request.
Here are some codes.
uploadDoc = (e) => {
e.preventDefault();
let file = e.target.files[0];
const url = 'https://api.agentcloud.com/api/leadfile/';
const formData = new FormData();
formData.append('lead', this.props.match.params.id);
formData.append('file',file);
const config = {
headers: {
'content-type': 'multipart/form-data',
'Authorization': 'Token 90406829e9d311b117bb7e1484a81e7b7f9f4551'
}
}
return post(url, formData, config);
}
Remove the content-type header, its incomplete.
When you use a form data object for ajax a proper content-type header is generated for you.¹
¹. I don't know react so this might only be part of the problem.
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.