如何将图像从URL追加到FormData-Javascript [英] How to append an image from URL to a FormData - Javascript

查看:646
本文介绍了如何将图像从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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆