How to upload files using jQuery's ajax functi

2019-03-06 08:05发布

问题:

Here's my nonworking attempt:

<script>
    function uploadImageSubmit() {

        var imageFile = $('.imageFile').val();

        $.ajax({

            url: 'ajax.php?request=upload-image&file='+imageFile,
            success: function(output) {
                 alert(output);                    
            }

        });

    }
</script>

<h2>Upload File</h2>

<form>
    <input type="file" class="imageFile" />
    <a onClick="uploadImageSubmit()">Upload</a>
</form>

The code on "ajax.php":

<?php

$action = $_GET['request'];

switch($action) {

    case 'upload-image':

        $imageFile =  $_GET['file'];

        $name = $_FILES[$imageFile] ['name'];
        $tmpLocation = $_FILES[$imageFile] ['tmp_name'];

            $upload = move_uploaded_file($tmpLocation, "files/$name");
            echo ($upload) ? $name.' uploaded successfully!' : 'File not uploaded.';

    end;

}

?>

I get the message file not uploaded. I think it's because even though strings can be passed via the url, File paths can't for some reason. But then again I have no idea why it's not working. Can someone figure out what's wrong please?

回答1:

Actually, HTML5 and the new File API does support uploading via XmlHttpRequest. It works beautifully in Firefox 4 and Chrome.



回答2:

XmlHttpRequest has no support to upload files. you need to use some hidden iframe or a flash solution.



回答3:

You can not upload file using plain JS/AJAX. A known trick is to post your file to a hidden iframe and update the iframe.