简体   繁体   English

使用formdata ajax上传图像发送到php

[英]upload image using formdata ajax send to php

I newbie in this webpage area and I was try to upload image to my file by using ajax and send it to php. 我是这个网页区域的新手,我尝试使用Ajax将图像上传到我的文件中并将其发送到php。 But I have done some coding here. 但是我在这里做了一些编码。 Can some one correct me where I'am wrong ? 有人可以纠正我哪里出错了吗? here is my form with file upload and a button 这是我的文件上传表格和一个按钮

<form method="post" enctype="multipart/form-data"  action="">
    <input type="file" name="images" id="images" multiple="" />

    <input type="submit" value="submit" id="harlo">
</form>

Once I click on button the file will send it here and receive the src and ajax to php file but I guess is about getting source problem. 一旦我点击按钮,文件将发送到这里并接收src和ajax到php文件,但是我想这是关于获取源代码的问题。 Need some one correct it for me. 需要一些为我纠正它。

(function upload() {

    var input2 = document.getElementById("harlo"), 

    formdata = false;



    if (window.FormData) {
        formdata = new FormData();

    }

    input2.addEventListener("click", function () {

        var i = 0, len = $('input[type="file"]')[0].files;

        for ( ; i < len.length; i++ ) {
            file = len.files[i];

            if (formdata) {
                formdata.append("images", file);
            }

        }

        if (formdata) {
            $.ajax({
                url: "upload.php",
                type: "POST",
                data: formdata,
                processData: false,
                contentType: false,
                success: function (res) {
                    document.getElementById("response").innerHTML =  res; 
                }
            });
        }
    }, false);
}());

<?php

    foreach ($_FILES["images"]["error"] as $key => $error) {
        if ($error == UPLOAD_ERR_OK) {
            $name = $_FILES["images"]["name"][$key];
            move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "uploads/" . $_FILES['images']['name'][$key]);
        }
    }

    echo "<h2>Successfully Uploaded Images</h2>";
?>

Use something like: 使用类似:

$("form").on("submit", function(
    // Your ajax request goes here
    $.ajax({
        url: "upload.php",
       type: "POST",
       data: $("form").serialize(),
       processData: false,
       contentType: false,
       success: function (res) {
          $("#response").innerHTML = res;
       }
    });

    return false;
));

But there seems to be a problem with sending files trough ajax anyway. 但是无论如何,通过ajax发送文件似乎存在问题。 Cause they're missed by the serialize() method because JS has no access to files content on users computer. 由于JS无法访问用户计算机上的文件内容,因此serialize()方法会丢失它们。 So the form must be sent to the server to get the file data. 因此,必须将表单发送到服务器以获取文件数据。

See here: https://stackoverflow.com/a/4545089/1652031 看到这里: https : //stackoverflow.com/a/4545089/1652031

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM