adding source(src) of image to formData and posting it to backend via http post call

Viewed 1118

I have an img tag with src="fast.jpg". I want to get the image picked from my source folder add it to form data and send it via http post call

html:

<img src="fast.jpg" data-highres="fast.jpg"  
style="width:150px;height:150px;"id="img1"  onclick="myFunction(this);" >

javascript:

var img = document.getElementById($(target).attr("id")).src

console.log("img>>>>",img)

var files = img.files
console.log("files", files)
var formData = new FormData();
formData.append('pic[]', img.name);

console.log("formdata>>", formData) 

post call:

    xhttp.open("POST", "http://127.0.0.1:5001/testpost", true);
    xhttp.withCredentials = false;
    xhttp.setRequestHeader("Content-type", "application/json");
    xhttp.setRequestHeader("cache-control", "no-cache", "no-cors");
    xhttp.send(formData);
2 Answers

You need add Content-type for XMLHttpRequest //Set header information along with the request

http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

And your file content is not correct, you need use input type="file" to select image, img tag only for preview upload image.

Make the image input inside a form with an id, and use:

<form id="myForm">
  <input type="file" name="myPicture">
</form>

In your js code, send the form, like so:

var formData = new FormData( $('form#myForm')[0] );
Related