简体   繁体   中英

How can I upload file with AJAX using PHP?

I want to upload file to server using AJAX and 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:

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

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

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

PHP Setup Guide: 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)!

As the error message is telling you, there is no 'file' member to the $_FILES associative array in PHP. 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
        },
    }); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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