如何使用PHP上传AJAX文件?

时间:2015-12-31 19:11:30

标签: javascript php jquery ajax

我想使用AJAX和PHP将文件上传到服务器。这是我到目前为止所尝试过的,但它对我不起作用。 服务器抛出此错误: - 注意:未定义的索引:第3行的C:\ xampp \ htdocs \ authentication \ test.php中的文件 注意:未定义的索引:第7行的C:\ xampp \ htdocs \ authentication \ test.php中的文件 注意:未定义的索引:第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>
&#13;
&#13;
&#13;

这是客户端代码,test.php:

&#13;
&#13;
<?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";
		}
    }

?>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:0)

使用jQuery File Upload插件,它有许多很酷的功能,可以节省更多时间,避免重新发明轮子。

库:
https://blueimp.github.io/jQuery-File-Upload/

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});
        });
    }

});

答案 1 :(得分:0)

这两行是错误的:

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

只使用一个版本的jQuery:1.5.1或2.1.4(我建议最后一个)!

答案 2 :(得分:0)

正如错误消息告诉您的那样,没有&#39;文件&#39; PHP中$ _FILES关联数组的成员。我想你想要&#39; name&#39;。

答案 3 :(得分:0)

这总是对我有用:

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
        },
    }); 
}