如何将图像从URL追加到FormData

如何将图像从URL追加到FormData

本文介绍了如何将图像从URL追加到FormData-Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的小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>

我不知道如何将URL附加到formData.

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

推荐答案

您可以执行两个XMLHttpRequest();通过将responseType设置为"blob",首先将GET请求图像作为Blob;然后将Blob响应附加到POST

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();

这篇关于如何将图像从URL追加到FormData-Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 19:13