使 AJAX 多文件上传正常工作


Getting AJAX multiple file upload to work properly

我一直在尝试让我的 AJAX 多文件上传脚本正常工作,但由于某种未知原因,它根本没有上传任何文件。我将发布任何相关的代码和已知的输出。希望你们知道一些进一步调试我的代码的方法,看看发生了什么。

HTML/Javascript (jQuery):

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="style.css" rel="stylesheet" />
        <script src="jquery-2.1.3.min.js"></script>
        <script src="dmuploader.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                function add_log(message){
                    var template = '<li>[' + new Date().getTime() + '] - ' + message + '</li>';
                    $('#debug').find('ul').prepend(template);
                }
                function add_file(id, file){
                    var template = '' +
                        '<div class="file" id="uploadFile' + id + '">' +
                        '<div class="info">' +
                        '#1 - <span class="filename" title="Size: ' + file.size + 'bytes - Mimetype: ' + file.type + '">' + file.name + '</span><br /><small>Status: <span class="status">Waiting</span></small>' +
                        '</div>' +
                        '<div class="bar">' +
                        '<div class="progress" style="width:0%"></div>' +
                        '</div>' +
                        '</div>';
                    $('#fileList').prepend(template);
                }
                function update_file_status(id, status, message){
                    $('#uploadFile' + id).find('span.status').html(message).addClass(status);
                }
                function update_file_progress(id, percent){
                    $('#uploadFile' + id).find('div.progress').width(percent);
                }
                $("#drag-and-drop-zone").dmUploader({
                    url: 'upload.php',
                    dataType: 'json',
                    allowedTypes: 'image/*',
                    onInit: function(){
                        add_log('Uploader geladen.');
                    },
                    onBeforeUpload: function(id){
                        add_log('Beginnen met uploaden van #' + id);
                        update_file_status(id, 'uploading', 'Uploading...');
                    },
                    onNewFile: function(id, file){
                        add_log('Nieuw bestand in de wachtrij geplaatst: #' + id);
                        add_file(id, file);
                    },
                    onComplete: function(){
                        add_log('Alle bestanden zijn geupload.');
                    },
                    onUploadProgress: function(id, percent){
                        var percentStr = percent + '%';
                        update_file_progress(id, percentStr);
                    },
                    onUploadSuccess: function(id, data){
                        add_log('Bestand #' + id + ' succesvol geupload.');
                        add_log('Server response for file #' + id + ': ' + JSON.stringify(data));
                        update_file_status(id, 'seccess', 'Upload Complete');
                        update_file_progress(id, '100%');
                    },
                    onUploadError: function(id, message){
                        add_log('Failed to Upload file #' + id + ': ' + message);
                        update_file_status(id, 'error', message);
                    },
                    onFileTypeError: function(file){
                        add_log('File ''' + file.name + ''' cannot be added: must be an image');
                    },
                    onFileSizeError: function(file){
                        add_log('File ''' + file.name + ''' cannot be added: size excess limit');
                    },
                    onFallbackMode: function(message){
                        alert('Browser not supported(do something else here!): ' + message);
                    }
                });
            });
        </script>
    </head>
    <body>
        <div class="wrapper">
            <h1>Foto's uploaden</h1>
            <div class="left-column">
                <!-- D&D Markup -->
                <div id="drag-and-drop-zone" class="uploader">
                    <div>Sleep de bestanden naar dit venster</div>
                    <div class="or">-of-</div>
                    <div class="browser">
                        <label>
                            <span>Klik hier om de bestandsbrowser to openen</span>
                            <input type="file" name="files[]" multiple="multiple" title='Click to add Files' />
                        </label>
                    </div>
                </div>
            </div>
            <div id="fileList">
            </div>
            <div id="debug">
                <h2>Informatie</h2>
                <div>
                    <ul>
                    </ul>
                </div>
            </div>
            <div id="footer">
                &copy; 2015
            </div>
        </div>
    </body>
</html>

PHP文件(这个似乎给人带来了一些麻烦):

<?php
for($i=0; $i<count($_FILES['file']['name']); $i++) {
    $tmpFilePath = $_FILES['file']['tmp_name'][$i];
    if ($tmpFilePath != ""){
        $newFilePath = "upload/" . $_FILES['file']['name'][$i];
        if(move_uploaded_file($tmpFilePath, $newFilePath)) {
            echo json_encode(array('status' => 'ok'));
        } else {
            echo json_encode(array('status' => 'Error: File can''t be moved.'));
        }
    }
}
?>

上传 1 个或多个文件时,JSON 返回Server response for file #0: {"status":"Error: File can't be moved."}

打印$_FILES['file']的内容时,它返回:

Array
(
    [name] => Certwell_IBF_9040_web-resized-image-238x238.jpg
    [type] => image/jpeg
    [tmp_name] => /tmp/phpNHgAaQ
    [error] => 0
    [size] => 13052
)

因此,脚本似乎确实按预期接收了文件。jQuery部分似乎工作得很好。唯一的问题是文件实际上并没有在服务器上上传(或保存?我确实检查了文件夹权限,还检查了/tmp文件夹(为空)。浏览器控制台不会返回任何错误。我还能做些什么来弄清楚发生了什么以及为什么它不起作用?

您需要确保/tmp文件夹可由Web服务器用户写入。我猜是阿帕奇?您需要检查是否www-data(例如 ubuntu 上的默认 apache 用户)。问题> chown -R www-data:www-data /tmp或问题> sudo chmod 777 /tmp

如果您不想篡改 /tmp linux 文件夹,您可以在 php.ini config http://php.net/manual/en/ini.core.php#ini.upload-tmp-dir 中的应用程序文件夹中设置自己的自定义/tmp文件夹。

在您的$newFilePath使用

$newFilePath = $_SERVER['DOCUMENT_ROOT'] ."/上传/";

来定义您的完整路径,以避免"文件无法移动"错误。

我认为您需要定义网站的根文件夹,例如

$basepath = "/home/yourWebpage/public_html/";

,然后使用此路径上传照片

for($i=0; $i<count($_FILES['file']['name']); $i++) {
$tmpFilePath = $_FILES['file']['tmp_name'][$i];
    if ($tmpFilePath != ""){
        $newFilePath = $basepath . "upload/" . $_FILES['file']['name'][$i]; // Here use the $basepath....
       if(move_uploaded_file($tmpFilePath, $newFilePath)) {
           echo json_encode(array('status' => 'ok'));
       } else {
           echo json_encode(array('status' => 'Error: File can''t be moved.'));
        }
    }