how to send a file with a body - javascript

I am working on React web app with a Flask backend. how can I send a file with JSON data on the body?
I try the code below but is not working
const file = e.target.file[0]
const user = [{name: 'Ma'}]
const formData = new FormData()
dormData.append('file', file)
dormData.append('user', user)
const post = await axios({
method: 'post',
url: 'http://127.0.0.1:5000/route',
data: formData,
headers: { "Content-Type": "multipart/form-data" }
})

You have to set the Content-Type header as application/json and you can set the body as your json
Your code would look something like this
const post = await axios({
method: 'post',
url: 'http://127.0.0.1:5000/route',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(myJson) //insert your stringified json here
})
Since you are creting a react web app, it's easy to structure a JSON from a form.

You are spelling formData wrong. Use this code:
formData.append('file', file)
formData.append('user', user)

Related

Can't send a multipart/form-data from a react view with axios

How to send a multipart/form-data from a javascript view to a rails controller?
I'm trying to make a form able to send a file (image) to my backend controller, so I am adding this on the headers of my Axios call:
axios.defaults.headers.common['Content-Type'] = 'multipart/form-data';
I add it within my functional component, anyways checking the network i see :
Content-Type: application/json;charset=UTF-8
and the parameters received in the controller are empty (for the file)
I have:
const handlePhoto = (e) => {
const image = new FormData();
image.append('photo', e.target.files[0]);
console.log("inside habdlephoto", image.get('photo'))
const dataSend = Object.assign({} ,data, image.get('photo'));
setData(dataSend)
}
which I use in
<Input
type="file"
innerRef={register}
name="photo"
onChange={handlePhoto}
multiple={true}
/>
the axios call looks like:
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
axios
.post("../../../api/v1/products/create.json", { product: {...data, ...dataRegister} }, config )
It seems that you are not setting the headers correctly for the request.
Try to set the headers via the request config:
const formData = new FormData();
formData.append('file',file)
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
axios.post(url, formData, config)

Axios post request not sending parameters

I have a scipt tag in which im making a post request to a route through axios.Axios is not sending the parameters through.
Here is the code for axios:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript">
const data={'firstName':"sai"}
axios({
url: "/",
method: "post",
data: data,
})
.then(response => {
console.log(response);
})
.catch(error => console.error(error));
</script>
Here is the express side of things:
app.post("/",function(req,res){
console.log("post route");
console.log(req.body);
})
Im console.logging the data coming from the post request with the help of req.body(I also have body-parser working just fine.Tested with other normal forms).The req comes through to hit the post route.BUt the body is empty always logs "{}".
Please help me out with this.
Option 1:
Define config object
let config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
}
Mandatory: Use array for params and not js object for 'application/x-www-form-urlencoded'
const params = new URLSearchParams();
params.append('PARAM1', 'VALUE1');
params.append('PARAM2', 'VALUE2');
Call post
axios.post( uri, params, config )
or
axios({
url,
headers: { 'content-type': 'application/x-www-form-urlencoded' }
data: params
})
Option 2:
Create an api instance (optional) and set default content-type
const api_local = axios.create({
baseURL: 'http://localhost:1000/myapi',
});
api_local.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Mandatory: Use array for params and not js object for 'application/x-www-form-urlencoded'
const params = new URLSearchParams();
params.append('PARAM1', 'VALUE1');
params.append('PARAM2', 'VALUE2');
Call post
api_local.post( uri, params )
I also have body-parser working just fine.Tested with other normal forms
Normal forms submit data encoded as either multipart/form-data or application/x-www-form-urlencoded.
Axios submits data, by default, as application/json.
You need a different body parser. One which supports JSON.
(Or to submit the data in a different format)

axios send image through post

I'm trying to send an image through axios POST request. The request is going through, but the image is not uploading.
Here is my code,
const screenshotPath = path.join(os.tmpdir(), 'screenshot.png');
var bodyFormData = new FormData();
//bodyFormData.append('uploadedFile', screenshotPath);
bodyFormData.append('uploadedFile', fs.createReadStream(screenshotPath));
axios({
method: 'post',
url: url,
data: bodyFormData,
config: {
headers: {
'Content-Type': 'multipart/form-data',
Authorization: 'Bearer ' + token
}
}
})
Is it because of the filename path ?
this is my screenshotPath
C:\Users\oem\AppData\Local\Temp\screenshot.png
You are using createReadStream function from the File System library of Node. But Node is running on server-side and here you are working with a react application which is running on client side.
Please check MDN documentation on how to upload files from front-end applications.

How to send values like form-data postman - react js

I'm using fetch to send value to my server. my server is php.
when I send my values with postman my server response as well.
but when I want to send my values with fetch I cannot get them from server side.
postman:
my requestOption:
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(parms)
};
my values sent to server but I cannot get them like postman form-data.
parms is a object variable. like:
var parms = {};
parms['tok'] = '35345345';
Just use formData as fetch body:
var formData = new FormData()
formData.append("tok", '35345345')
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json'
},
body: formData
};

Upload Excel File from React to C# ASP.NET Core backend

I am trying to upload a file from a react front end to a C# backend. I am using drop zone to get the file and then I call an api helper to post the file but I am getting different errors when I try different things. I am unsure exactly what the headers should be and exactly what I should send but I get two distinct errors. If I do not set the content-type I get 415 (Unsupported Media Type) error. If I do specify content type as multipart/form-data I get a 500 internal server error. I get the same error when the content-type is application/json. The url is being past in and I am certain it is correct. I am unsure if the file should be appended as file[0][0] as I have done or as file[0] as it is an array but I believe it should be the first. Any suggestions welcome :) Here is my api post helper code:
export const uploadAdminFile = (file, path, method = 'POST', resource =
config.defaultResource) => {
const url = createUrl(resource, path);
const data = new FormData();
data.append('file', file[0][0]);
data.append('filename', file[0][0].name);
const request = accessToken =>
fetch(
url,
{
method,
mode: 'cors',
withCredentials: true,
processData: false,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json', //'multipart/form-data',
Authorization: `Bearer ${accessToken}`,
},
body: data,
})
.then(res => res.json())
.then(success => console.log('API HELPER: file upload success: ', success)
.catch(err => console.log('API HELPER: error during file upload: ', err)));
return sendRequest(request, resource);
};
Thanks for the help and suggestions, it turned out to be a backend issue but even still I learned a lot in the process. I will post my working code here in case anyone comes across this and finds it useful.
export const uploadAdminFile = (file, path, resource=config.defaultResource) => {
const url = createUrl(resource, path);
const formData = new FormData();
formData.append('file', file[0][0]);
formData.append('filename', file[0][0].name);
const request = accessToken =>
fetch(url,
{
method: 'POST',
headers: {
Accept: 'application/json',
Authorization: `Bearer ${accessToken}`,
},
body: formData,
});
return sendRequest(request, resource);
};
As mentioned, the file name does not need to be sent separately and count be omitted. I am indexing the file this way because I get it from dropzone as an array and I only want a single file (the first one in the array). I hope this helps someone else out and here is a link to the mdn fetch docs (good information) and a good article on using fetch and formData.

Categories

Resources