【问题标题】:How to upload files using jQuery's ajax function with PHP?如何使用 jQuery 的 ajax 函数和 PHP 上传文件?
【发布时间】:2011-07-13 06:47:54
【问题描述】:

这是我的非工作尝试:

<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>

“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;

}

?>

我收到未上传的消息文件。我认为这是因为即使字符串可以通过 url 传递,文件路径也不能出于某种原因。但是话又说回来,我不知道为什么它不起作用。请问有大神能看一下怎么回事吗?

【问题讨论】:

标签: php jquery ajax file-upload


【解决方案1】:

其实HTML5 and the new File API确实支持通过XmlHttpRequest上传。它在 Firefox 4 和 Chrome 中运行良好。

【讨论】:

    【解决方案2】:

    您不能使用纯 JS/AJAX 上传文件。一个已知的技巧是将文件发布到隐藏的 iframe 并更新 iframe。

    【讨论】:

      【解决方案3】:

      XmlHttpRequest 不支持上传文件。您需要使用一些隐藏的 iframe 或 Flash 解决方案。

      【讨论】:

        猜你喜欢
        • 2012-05-16
        • 2017-02-15
        • 1970-01-01
        • 2014-07-05
        • 2021-09-09
        • 2018-05-30
        相关资源
        最近更新 更多