How to call post API with image attached in body using javascript - javascript

I want to to call post API with image attached in body. I have browsed and tried available solutions but didnt work(getting 400 as error). Solutions tried -
File which is browsed I have created a filereader object and called readAsDataURL(). It gave undefined error(bad request error)
let reader = new FileReader()
reader.readAsDataURL(event.target.files[0]);
fetch('some endpoint, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: reader, //(reader.result also i tried)
})
.then((response) => response.json())
.then((json) => console.log(json))```
Second approach was creating a dataform, even this gave bad request as error
<form class="form" id="myForm">
<input type="file" id="fileUpload" accept="image/*" onchange="previewImage(event);"/>
</form>```
```const inpFile = document.getElementById('fileUpload');
const formData = new FormData();
formData.append('inpFile', event.target.files[0]);
fetch(some endpoint, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: formData,
})
.then((response) => response.json())
.then((json) => console.log(json))```
screenshot of error

The second approach is correct except your headers. try changing them to 'Content-Type': 'multipart/form-data'.
you are not posting JSON data but FormData.

Related

Using Axios put to upload PDF files to S3 bucket via API gateway

I am trying to upload PDF file to S3 Bucket in react js. I have created an API through API gateway to expose put method of S3 objects.
It works fine when I try to upload file with "put" method of fetch whereas axios put uploads the file without body.
Here's my Fetch code:
function handleChange(event) {
setFile(event.target.files[0])
}
const handleClick = (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('file', file);
const filename = file.name;
fetch(`${PutEndPoint}/${filename}`,
{
method:'Put',
headers: {
'Content-Type': 'application/pdf',
},
body :formData
//JSON.stringify({ title: 'Fetch PUT Request Example' })
})
.then(response => response.json())
.then(json => console.log(json))
Axios code:
function handleChange(event) {
setFile(event.target.files[0])
}
const handleClick = (e) => {
e.preventDefault();
const formData = new FormData();
const filename = file.name;
console.log(file.name);
formData.append('file', file);
console.log(formData)
axios(`${PutEndPoint}/${filename}`,
{
method:'Put'
headers: {
'Content-Type': 'application/pdf',
},
formData
})
.then(response => response.json())
.then(json => console.log(json))
HTML:
<input type='file' name="file" onChange={handleChange}></input>
<Button onClick= {handleClick}>
Upload
</Button>
I have tried:
Use content-type as multipart/form-data
Remove content-Type from header
Add file name as third argument to append
formData.append('file', file, file.name);
Change content-type of API to accept multipart/form-data
None of this has worked.
As per docs, the syntax has to look like this:
// Send a PUT request
axios({
method: 'put', // the request method to be used when making the request request
url: '`${PutEndPoint}/${filename}`', // the server URL that will be used for the request,
headers: {'Content-Type': 'application/pdf'}, // custom headers to be sent
data: formData // --> the data to be sent as the request body
});
// data is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
// When no transformRequest is set, must be of one of the following
types:
// - string, plain object, ArrayBuffer, ArrayBufferView,
URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream, Buffer
See https://github.com/axios/axios#axios-api

imgur api image uploading cross origin resource sharing error

hope you all doing fine,
currently i am working on a small html static project and i have image uploading there so i used imgur api, i tested it out on postman it seems pretty okay, but when i try to code it like that
var myHeaders = new Headers();
myHeaders.append("Authorization", "Client-ID ******");
myHeaders.append("Access-Control-Allow-Origin", "*");
var formdata = new FormData();
formdata.append("image", image);
var requestOptions = {
method: "POST",
headers: myHeaders,
body: formdata,
redirect: "follow",
};
fetch("https://api.imgur.com/3/upload", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
i only got this error
cross origin resource sharing error header disallowed preflight response
am i doing something wrong here

How to fix the "Multipart request" error?

I have an input to upload files and I want to save the file in a server. I used postman and everything works fine but its in the code where things get messy. Im getting this error everytime I click the button
"{"httpStatus":"Internal Server Error","httpStatusCode":500,"status":"ERROR","message":"Current request is not a multipart request"}"
my code:
const handleFile= (data) => {
setFile(data.target.files[0]);
};
const sendJson = () => {
formdata.append("file", file);
const requestImage = {
method: "POST",
headers: myHeaders,
body: formdata,
};
fetch(urlFiles, requestImage)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
}
return (
<input
style={{ display: "none" }}
id="upload-photo"
name="upload-photo"
type="file"
onChange={handleFile}
inputRef={register}
/>
<Button
variant="contained"
color="primary"
typeof={"submit"}
onClick={(() => sendJson())}
>
Registar
</Button>
)
What this error means and how can I fix this? I tried some solutions like adding enctype="multipart/form-data" in the form tag but nothing is working. Please help me with this
The standard way of making a multipart request using fetch is as follows,
const formData = new FormData();
formData.append('myFile', fileInput.files[0]);
fetch(url, {
method: 'POST',
body: formData
}).then(res => response.json()).then(console.log).catch(console.error);
DO NOT set the Content-Type header. The browser will set it for you along with something called disposition. To learn about multipart forms, I've written a blog on it. https://dev.to/sidthesloth92/understanding-html-form-encoding-url-encoded-and-multipart-forms-3lpa

what are the differences between these three different ways of submitting form data via a POST request

I am learning front end development and I learned there are essentially 3 ways to submitted data from a form using via a POST request.
let url = 'https://somewebsite.com/mock/login'
let data = {username:'admin', password:'123456'}
fetch(url, {
method:'POST',
headers: {
'Content-Type' : 'application/x-www-form-urlencoded'
},
body: Object.entries(data).map(pair => pair[0] + '=' + pair[1]).join('&')
})
fetch(url, {
method:'POST',
headers: {
'Content-Type' : 'application/json'
},
body: JSON.stringify(data)
})
let formData = new FormData()
formData.append('username', data.username)
formData.append('password', data.password)
fetch(url, {
method:'POST',
headers: {
'Content-Type' : 'multipart/form-data',
},
body: formData
})
But I don't really know the implications and differences among these three. What is the best practice?
I only know that , we have to use new FormData() when uploading anything else but text, like a single image or multiple images, a blob, along with 'Content-Type': 'multipart/form-data'
And I guess the other two options that I showed below differ in how the sent data is encoded.

How to POST a blob and JSON values using fetch

I am passing a blob image file to a server using the header,
application/octet-stream.
I need to also pass some string values to the server with it. If I change the header to
application/json
I can access the string, but the blob becomes undefined.
Example
const data = {
blob,
firstname: 'Nichoals',
};
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.blob())
.then(blob => {
...
})
.catch(error => console.log(error));
},
'image/png',
1,
);
Things I have tried
I have tried to pass the data using FormData() and was able to get the data to the server but the file was corrupt. I do think I could figure out how to get it to work this way but I would like to learn a better way to do it if possible.
Things I do not want to do
I do not want to convert the blob to a string because I fear that will be way to expensive.
Question
In what way can I POST an object with a blob and some string values inside of it to a server without using the way mentioned above?
Essentially this,
const data = {
blob,
firstname: 'Will',
};
You could send the json as a header:
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/octet-stream',
'Custom-Json': JSON.stringify(data)
},
body: blob,
}).then(response => response.blob())
.then(blob => {
// handle response
})
.catch(error => console.log(error));

Categories