[英]How to make formData object from image URL
我想從網址上傳圖片,例如:http://..../logo.png我需要從圖片網址制作formData對象,但它不起作用:
HTML:
<form id="form-url">
<input type="text" class="image" id="textarea" placeholder="URL" />
<button>UPLOAD</button>
</form>
Javascript:
$("#form-url").submit(function(e) {
if ($(".image").val() != "URL" && $(".image").val() != "") {
//I also tried this:
var data;
var img = new Image();
img.src = $(".image").val();
img.load = function(){
data = getBase64Image($(".image").val());
};
//but it send undefined
//and this:
var data = URL.createObjectURL($(".image").val()); //dont work
//error: TypeError: Argument 1 is not valid for any of the 1-argument overloads of URL.createObjectURL.
//Upload process working on normal input type file uploading but no on URL image
var formData = new FormData(data);
formData.append("fileToUpload", data);
var xhr = new XMLHttpRequest();
xhr.open('POST', "upload_ajax.php", true);
xhr.onload = function () {
if (xhr.status === 200) {
data = xhr.responseText;
datas = data.split("_");
if (datas[0] != "true") {
alert(data);
} else {
alert('YES');
}
} else {
alerter('An error occurred while uploading this file! Try it again.');
}
};
xhr.send(formData);
} else { alerter("Your file must be an image!"); }
return false;
});
我的用於調試的php腳本:
<?php
if (isset($_POST)) {
var_dump($_POST);
if (empty($_FILES['fileToUpload']['tmp_name'])) {
echo "Your file must be an image!";
} else {
echo $_FILES['fileToUpload']['name'];
echo $_FILES['fileToUpload']['size'];
}
}
?>
感謝您提供的所有幫助和時間。.對於我的英語不好(學生),我們深表歉意。
如果getBase64Image
來自here ,或者getBase64Image
相似。
那么您使用它是錯誤的。 您需要將圖像節點本身傳遞給它。 同樣,圖像onload事件也是異步的,因此您必須等待它完成才能獲取數據並發送它。
var xhr = new XMLHttpRequest();
var formData = new FormData();
xhr.open('POST', "upload_ajax.php", true);
...
var img = new Image();
img.onload = function(){
var data = getBase64Image(this);
formData.append("fileToUpload", data);
xhr.send(formData);
};
還要注意在服務器端,您將需要從base64編碼中對其進行解碼,因為它是通過字符串發送的,它將以$_POST
而不是$_FILE
var rawContents = base64_decode($_POST['fileToUpload']);
請注意,您也可以將網址發送到php腳本,並讓php獲取圖像數據
var rawContents = file_get_contents($_POST['imageurl']);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.