问题
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.
回答1:
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();
来源:https://stackoverflow.com/questions/37241882/how-to-append-an-image-from-url-to-a-formdata-javascript