JQuery AJAX sending files array from form

2019-02-26 09:37发布

问题:

I got this code somewhere to upload pics without refreshing the browser. However I didn't like the uploader file so I decided to use the old one I used to work with. The problem is that it is sending an array instead of a string from the javascript file (it was intended to be sent multiple files instead of only one). Here is the code that makes the array:

input.addEventListener("change", function (evt) {
    document.getElementById("response").innerHTML = "Loading . . ."

    var i = 0, len = this.files.length, img, reader, file;

    for ( ; i < len; i++ ) {
        file = this.files[i];
            if (formdata) {
                formdata.append("uploaded_file[]", file);
    }   }   }

    if (formdata) {
        $.ajax({
            url: "img_upload.php",
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false
        }).done(function (res) {
                            /* *** show uploaded item *** */
                            /* *** show response *** */
            });
    }

My knowledge in Javascript is really weak and I can't find out how to modify this code to send the uploaded file by itself instead of an array.

I tried these independently, but none of them worked (send_img is the form name/id):

formdata = document.send_img.uploaded_file.value;
formdata = document.getElementById("uploaded_file");
formdata = new formdata ($('#send_img'));
formData = $('#send_img').serialize();
formdata.replaceWith("uploaded_file[]", file);

I also tried eliminating the for to use the same key (0) but it doesn't work that way. The condensed code for img_upload.php is:

$fileName = $target . $_FILES["uploaded_file"]["name"];
$fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"];
$fileName = $new_name .  "."  . $fileExt;
move_uploaded_file($fileTmpLoc, "images/images/temp/$fileName");

How can I send the uploaded file (or header or whatever it is supposed to send) in just one string and, in case of a second file being added, replace the first one instead of creating a second value in the array?

回答1:

The problem is not your logic, the problem is that files cannot be uploaded via ajax.

But maybe you will ask, how did others do? Well, try a form plugin (another .js that works with jQuery)

I found this for you, it works using 'submit' method but maybe you can do a submit when input change or find other kind of solution with javascript actions.

Check this: http://www.miguelmanchego.com/2009/subir-archivos-usando-ajax-jquery/

Website is in Spanish but translate it to English if you need. Also that link includes a live example and source-code download.

Regards.



回答2:

Below is my ajax settings which can upload files

method: "POST",
        url: url,
        headers: { 'Content-Type': undefined },
        transformRequest: function (data, headersGetter) {
            var formData = new FormData();
            angular.forEach(data, function (value, key) {
                if (Array.isArray(value)) {
                    // To save array of items
                    angular.forEach(value, function (value1, key1) {
                        if (value1.constructor.name != "File") {
                            angular.forEach(value1, function (value2, key2) {
                                formData.append(key + '[' + key1 + '].' + key2, value2);
                            });
                        }
                    });
                } else {
                    formData.append(key, value);
                }
            });

            return formData;
        },
        enctype: 'multipart/form-data',
        dataType: 'json',
        traditional: true,
        data: data,
        cache: false,
        processData: false,
        contentType: false