如何从图像URL生成formData对象

时间:2014-04-07 16:59:34

标签: javascript php image url upload

我想从网址上传图片,例如:http:// .. ../logo.png 我需要从图像url创建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'];
        }
    }
?>

感谢您的所有帮助和时间.. 抱歉我的英语不好(学生)

1 个答案:

答案 0 :(得分:0)

如果getBase64Image来自here,或与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); }; 相似。

然后你错了。您需要将图像节点本身传递给它。图像onload事件也是异步的,因此你必须等待它完成以获取数据并发送它。

$_POST

另请注意,在服务器端,您需要从base64编码解码它,因为它是通过字符串发送的,它将在$_FILE而不是var rawContents = base64_decode($_POST['fileToUpload']);

var rawContents = file_get_contents($_POST['imageurl']);

请注意,您也可以将网址发送到php脚本,然后让php获取图片数据

{{1}}