Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append an image from URL to a FormData - Javascript

This is my little javascript code:

<script>

var formData = new FormData();

URL = "view.php?fetchImageById=1";

formData.append("imageFile", ....);

formData.append("author","user");
formData.append("description","image");

x=new XMLHttpRequest();
x.open("POST","upload.php",true);
x.setRequestHeader("Content-type", "multipart/form-data");
x.setRequestHeader("Content-Length",formData.length);
x.send(formData);
</script>

I don't know how to append the URL to the formData.

like image 550
Diego Lopez Avatar asked Jan 06 '23 02:01

Diego Lopez


1 Answers

You could perform two XMLHttpRequest()s; first GET request image as a Blob first by setting responseType to "blob"; then append Blob response to FormData at POST

var formData = new FormData();   
URL = "view.php?fetchImageById=1";    
var x;

var request = new XMLHttpRequest();
request.responseType = "blob";
request.onload = function() {
  formData.append("imageFile", request.response);
  formData.append("author","user");
  formData.append("description","image");
  x = new XMLHttpRequest();
  x.open("POST","upload.php",true);
  x.setRequestHeader("Content-type", "multipart/form-data");
  x.setRequestHeader("Content-Length", formData.length);
  x.send(formData);
}
request.open("GET", URL);
request.send();
like image 139
guest271314 Avatar answered Jan 08 '23 15:01

guest271314