Ajax没有将文件上传数据发送到php

时间:2014-02-16 20:27:55

标签: php jquery ajax

我一直无法让我的ajax脚本正确发布到我的php文件。我已经做了各种检查,我的ajax肯定是在注册图像文件,但它没有发布到php(它没有数据集)。知道文件没有发布的原因吗?这是AJAX和PHP:

$(function()
{
// Variable to store your files
var files;

// Add events
$('input[type=file]').on('change', prepareUpload);
$("form").submit(function(event){
    event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening

    // START A LOADING SPINNER HERE

    // Create a formdata object and add the files
    var data = new FormData();

    $.each(files, function(key, value)
    {
        console.log(files);
        data.append(key, value);
    });

    $.ajax({
        url: '../api/frs-upload.php',
        type: 'POST',
        data: data,
        cache: false,
        dataType: 'json',
        processData: false, // Don't process the files
        contentType: false, // Set content type to false as jQuery will tell the server its a query string request
        success: function(data, textStatus, jqXHR)
        {
            if(typeof data.error === 'undefined')
            {
                // Success so call function to process the form
                submitForm(event, data);
            }
            else
            {
                // Handle errors here
                console.log('ERRORS: ' + data.error);
            }
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            // Handle errors here
            console.log('ERRORS: ' + textStatus);
            // STOP LOADING SPINNER
        }
    });
});

// Grab the files and set them to our variable
function prepareUpload(event)
{
    files = event.target.files;
    for (var i = 0, file; file = files[i]; i++) {
        console.log(file);
    }
}

// Catch the form submit and upload the files
function uploadFiles(event)
{
    event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening

    // START A LOADING SPINNER HERE

    // Create a formdata object and add the files
    var data = new FormData();

    $.each(files, function(key, value)
    {
        alert("test");

        alert(key + ": " + value)
        data.append(key, value);
    });


    $.ajax({
        url: '/api/frs-upload.php?files',
        type: 'POST',
        data: data,
        cache: false,
        dataType: 'json',
        processData: false, // Don't process the files
        contentType: false, // Set content type to false as jQuery will tell the server its a query string request
        success: function(data, textStatus, jqXHR)
        {
            if(typeof data.error === 'undefined')
            {
                // Success so call function to process the form
                submitForm(event, data);
            }
            else
            {
                // Handle errors here
                console.log('ERRORS: ' + data.error);
            }
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            // Handle errors here
            console.log('ERRORS: ' + textStatus);
            // STOP LOADING SPINNER
        }
    });
}

function submitForm(event, data)
{
    // Create a jQuery object from the form
    $form = $(event.target);

    // Serialize the form data
    var formData = $form.serialize();

    // You should sterilise the file names
    $.each(data.files, function(key, value)
    {
        formData = formData + '&filenames[]=' + value;
    });

    $.ajax({
        url: 'submit.php',
        type: 'POST',
        data: formData,
        cache: false,
        dataType: 'json',
        success: function(data, textStatus, jqXHR)
        {
            if(typeof data.error === 'undefined')
            {
                // Success so call function to process the form
                console.log('SUCCESS: ' + data.success);
            }
            else
            {
                // Handle errors here
                console.log('ERRORS: ' + data.error);
            }
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            // Handle errors here
            console.log('ERRORS: ' + textStatus);
        },
        complete: function()
        {
            // STOP LOADING SPINNER
        }
    });
}
});

PHP:

<?php
if($_FILES['file']['name']){
$data = array();

    $error = false;
    $files = array();

    $uploaddir = 'uploads/';
    $uploadfile = $uploaddir . $_FILES["file"]["name"];
    $filename = $_FILES["file"]["name"];

        if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)){
            $files[] = $uploaddir .$file['name'];
        } else {
            $error = true;
        }
    $data = ($error) ? array('error' => 'There was an error uploading your files in: ' . $filename) : array('files' => $files);



echo json_encode($data);
} else {
echo json_encode(array('error' => 'No data set'));
}

2 个答案:

答案 0 :(得分:0)

请注意,并非所有浏览器都支持通过AJAX上传文件。您的脚本可能正常,但您的浏览器可能是问题。我建议使用iframe来执行此操作。您可以使用标记中的target属性将表单提交到iframe。

请查看http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html了解更多详情。

答案 1 :(得分:0)

根据Musa的说法,我使用$ _FILE ['0']代替$ _FILE ['name'],这解决了我的问题。当我查看控制台并打印出我的数据时,键是0,所以我应该看到这个..答案是检查你的密钥是什么。