如何将图像从 URL 附加到 FormData - Javascript
How to append an image from URL to a FormData - Javascript
这是我的小javascript代码:
<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。
你可以执行两个 XMLHttpRequest()
;首先 GET
通过将 responseType
设置为 "blob"
来请求图像作为 Blob
;然后在 POST
处将 Blob
回复附加到 FormData
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();
这是我的小javascript代码:
<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。
你可以执行两个 XMLHttpRequest()
;首先 GET
通过将 responseType
设置为 "blob"
来请求图像作为 Blob
;然后在 POST
Blob
回复附加到 FormData
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();