简体   繁体   English

如何使用PHP使用AJAX上传文件?

[英]How can I upload file with AJAX using PHP?

I want to upload file to server using AJAX and PHP. 我想使用AJAX和PHP将文件上传到服务器。 Here is what I've tried so far but it is not working for me. 到目前为止,这是我尝试过的方法,但不适用于我。 The server throws this error:- Notice: Undefined index: file in C:\\xampp\\htdocs\\authentication\\test.php on line 3 Notice: Undefined index: file in C:\\xampp\\htdocs\\authentication\\test.php on line 7 Notice: Undefined index: file in C:\\xampp\\htdocs\\authentication\\test.php on line 7 Client side code: 服务器引发此错误:-注意:未定义的索引:第3行的C:\\ xampp \\ htdocs \\ authentication \\ test.php中的文件注意:未定义的索引:第C行的C:\\ xampp \\ htdocs \\ authentication \\ test.php中的文件7注意:未定义的索引:第7行上C:\\ xampp \\ htdocs \\ authentication \\ test.php中的文件:客户端代码:

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Form Generator</title> <link rel="stylesheet" type="text/css" href="style.css" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script> <script type="text/javascript" src="jquery-2.1.4.js"></script> <script type="text/javascript"> function valid(){ var file_data = $('#sortpicture').prop('files')[0]; var form_data = new FormData(); form_data.append('file', file_data); alert(form_data); $.ajax({ url: 'test.php', // point to server-side PHP script dataType: 'text', // what to expect back from the PHP script, if anything cache: false, contentType: false, processData: false, data: form_data, type: 'post', success: function(data){ $('#result').html(data); // display response from the PHP script, if any } }); } </script> </head> <body> <div id='result'></div> <input id="sortpicture" type="file" name="sortpic" /> <button id="upload" onclick='valid()'>Upload</button> </body> </html> 

And here is client side code, test.php: 这是客户端代码test.php:

 <?php if ( 0 < $_FILES['file']['error'] ) { echo 'Error: ' . $_FILES['file']['error'] . '<br>'; } else { if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name'])){ echo "file uploaded"; } } ?> 

Use jQuery File Upload Plugin, It has many cool feature which will save more time and avoid re-inventing the wheel again. 使用jQuery File Upload Plugin,它具有许多很酷的功能,可以节省更多时间并避免再次发明轮子。

Library: 图书馆:
https://blueimp.github.io/jQuery-File-Upload/ https://blueimp.github.io/jQuery-File-Upload/

PHP Setup Guide: https://github.com/blueimp/jQuery-File-Upload/wiki/Setup PHP安装指南: https : //github.com/blueimp/jQuery-File-Upload/wiki/Setup

$(function () {
    'use strict';

    // Initialize the jQuery File Upload widget:
    $('#fileupload').fileupload({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        url: 'server/php/'
    });

    // Enable iframe cross-domain access via redirect option:
    $('#fileupload').fileupload(
        'option',
        'redirect',
        window.location.href.replace(
            /\/[^\/]*$/,
            '/cors/result.html?%s'
        )
    );

    if (window.location.hostname === 'blueimp.github.io') {
        // Demo settings:
        $('#fileupload').fileupload('option', {
            url: '//jquery-file-upload.appspot.com/',
            // Enable image resizing, except for Android and Opera,
            // which actually support image resizing, but fail to
            // send Blob objects via XHR requests:
            disableImageResize: /Android(?!.*Chrome)|Opera/
                .test(window.navigator.userAgent),
            maxFileSize: 999000,
            acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
        });
        // Upload server status check for browsers with CORS support:
        if ($.support.cors) {
            $.ajax({
                url: '//jquery-file-upload.appspot.com/',
                type: 'HEAD'
            }).fail(function () {
                $('<div class="alert alert-danger"/>')
                    .text('Upload server currently unavailable - ' +
                            new Date())
                    .appendTo('#fileupload');
            });
        }
    } else {
        // Load existing files:
        $('#fileupload').addClass('fileupload-processing');
        $.ajax({
            // Uncomment the following to send cross-domain cookies:
            //xhrFields: {withCredentials: true},
            url: $('#fileupload').fileupload('option', 'url'),
            dataType: 'json',
            context: $('#fileupload')[0]
        }).always(function () {
            $(this).removeClass('fileupload-processing');
        }).done(function (result) {
            $(this).fileupload('option', 'done')
                .call(this, $.Event('done'), {result: result});
        });
    }

});

These two lines are wrong: 这两行是错误的:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery-2.1.4.js"></script>

Use only one version of jQuery: 1.5.1 or 2.1.4 (I suggest the last one)! 仅使用jQuery的一个版本:1.5.1或2.1.4(我建议使用最后一个)!

As the error message is telling you, there is no 'file' member to the $_FILES associative array in PHP. 错误消息告诉您,PHP中的$ _FILES关联数组没有'file'成员。 I think you want 'name'. 我想你要“名字”。

This works for me always: 这始终对我有效:

function valid(){
    var formData = new FormData();
    formData.append('file', $("#sortpicture")[0].files[0]);
    $.ajax({
        url: "test.php",
        type: 'POST',
        dataType: 'json',
        processData: false,
        contentType: false,
        data: formData,
        success: function(data){
            // Process response here. May be preview image?
        },
        error: function(r){
            // Handle errors
        },
    }); 
}

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

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