简体   繁体   English

如何使用jQuery的ajax函数和PHP上传文件?

[英]How to upload files using jQuery's ajax function with PHP?

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": “ 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. 我认为这是因为即使可以通过url传递字符串,但由于某些原因文件路径也不能。 But then again I have no idea why it's not working. 但是话又说回来,我不知道为什么它不起作用。 Can someone figure out what's wrong please? 有人可以找出问题所在吗?

XmlHttpRequest has no support to upload files. XmlHttpRequest不支持上传文件。 you need to use some hidden iframe or a flash solution. 您需要使用一些隐藏的iframe或Flash解决方案。

You can not upload file using plain JS/AJAX. 您不能使用纯JS / AJAX上传文件。 A known trick is to post your file to a hidden iframe and update the iframe. 一个已知的技巧是将文件发布到隐藏的iframe并更新iframe。

Actually, HTML5 and the new File API does support uploading via XmlHttpRequest. 实际上, HTML5和新的File API确实支持通过XmlHttpRequest上传。 It works beautifully in Firefox 4 and Chrome. 它在Firefox 4和Chrome中运行良好。

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

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