Sitemap

Member-only story

Upload image data from local file

With incorrect headers, the response returns 401.

3 min readApr 21, 2020
Photo by Ashwini Chaudhary on Unsplash

Failure in my case

I was trying to post image data from local PC area as well as from Smartphone. I have been using XMLHttpRequest by adding an extra header with queries so that server-side can catch them. All is fine if I post metadata such a string, however when I have to post image data, server-side, that is PHP, could not parse the sent data. Thus, I researched how to upload image data. In this post, I’m going to expose the result of my struggling.

RequestHeader

urlencoded

First of all, I will put a couple of code below when I post metadata to server but less code is highlighted.

const xhr = new XMLHttpRequest()
const url = "path/to/server/api"
const metadata = {name, id, title, description}
xhr.onreadystatechange = () => {
if (xhr.status === 200) {
// TODO...
}
}
xhr.open("post", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xhr.send(metadata)

What the highlighted code is setRequestHeader. I have set “application/x-www-form-urlencoded”. This Content-type imply to use parameters as a query string in URL, such as…

--

--

No responses yet