簡體   English   中英

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

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

我想使用AJAX和PHP將文件上傳到服務器。 到目前為止,這是我嘗試過的方法,但不適用於我。 服務器引發此錯誤:-注意:未定義的索引:第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> 

這是客戶端代碼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"; } } ?> 

使用jQuery File Upload Plugin,它具有許多很酷的功能,可以節省更多時間並避免再次發明輪子。

圖書館:
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});
        });
    }

});

這兩行是錯誤的:

<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(我建議使用最后一個)!

錯誤消息告訴您,PHP中的$ _FILES關聯數組沒有'file'成員。 我想你要“名字”。

這始終對我有效:

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