简体   繁体   中英

Upload file after javascript processing, no ajax

I am attempting to process a user-uploaded file in javascript and then upload the file to the server. Once the processing is complete, I want the upload to work as it would have if I had not interrupted it with javascript. That is, I want to send a POST request to something like "receive_file.php" where the form validation, move_uploaded_file(), and a "successful upload" message to the user will occur. I have tried this in jquery, and I get an UPLOAD_ERR_NO_FILE from php:

function upload(file) {

    var form = $("<form/>", {
        enctype: "multipart/form-data",
        method: "POST",
        action: "/path/to/recieve_file.php"
    });

    form.append($("<input/>", {
        type: "file",
        name: "audio_file",
        value: file
    }));

    form.submit();
}

As far as I can tell, its not possible to write to an input type="file", only read from it. Still haven't found a great answer for this one, but what I have settled on is overwriting the current document with the response from an ajax request like so:

var fd = new FormData();
fd.append("audio_file", file);

var xhr = new XMLHttpRequest();
xhr.open('POST', 'recieve.php', true);

xhr.onreadystatechange = function() {

    if (xhr.readyState == 4 && xhr.status == 200) {
        document.open();
        document.write(xhr.response); // just overwrite the whole current document with "recieve.php"
        document.close();
    }

};

xhr.send(fd);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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