使用jQuery从通过AJAX一个多/表单数据发送数据 [英] Using jQuery to send data from a multipart/form-data through ajax

查看:144
本文介绍了使用jQuery从通过AJAX一个多/表单数据发送数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在这一整天了,我只是无法得到它的工作。

I've been working on this all day now, and I just can't get it working.

我已经基本得到了使用jQuery库一个简单的Ajax请求,我想送我通过mutlipart / form-data的文件输入后的数据,但是,我已经尝试了所有我能想到的。

I have basically got a simple ajax request using the jQuery library and I want to send the data which I post through a mutlipart/form-data file input, however, I have tried everything I can think of.

我的文件上传脚本已经就位等待文件名作为参数(试过也没有),但它只是不希望从文件输入框本身获得的数据。

My File upload script is in place awaiting the file name as a parameter (tried without also), but it just doesn't want to get the data from the file input box itself.

可能有人请赐教如何做到这一点没有另一个插件(多载等)。

Could someone please enlighten me on how to do this without another plugin (multiple upload, etc).

下面是我的jQuery code此位:

Here is my jQuery Code for this bit:

功能uploadTimesheets(){

function uploadTimesheets(){

$('#waiting').show();

var error = '';

var msg = '';

//Performs the Ajax Request
 var data = $.ajax({
    type        :   'POST',
    url         :   '/ajax/timesheet/uploadNewTimesheets.php',
    dataType    :   'json',
    contentType :   'multipart/form-data',
    data        :   data,
    error       :   error,
    msg         :   msg,
    success     :   function(data){

        if(!data){
            $('#notification').removeClass(this).addClass('notification-success').html(data).show().delay(1200).fadeOut(800);
            getActiveTimesheets(getSelectedPage());
        }else{
            $('#notification').removeClass().addClass('notification-error').html(data.msg + data.errorList).show();
            alert('PHHAIL');
        }

        $('#waiting').hide();
        function(xhr, status, errorThrown){
            $('#waiting').hide();
        }
    }
});

}

这里是我的PHP上传脚本:

And here is my PHP upload script:

    /**
 * Creates a directory in the active directory with the given folder name
 *
 * @author  RichardC
 * @param   string    $dirName
 * @return  boolean
 */
public function createDir( $dirName ) {

    $docRoot = getenv('DOCUMENT_ROOT');

    if (!is_dir(sprintf('%s/%s', $docRoot, $dirName))) {
        $makeDir = mkdir(sprintf('%s/%s', $docRoot, $dirName));
        echo sprintf('Creating a folder called \'/%s/\' ...', $dirName);
        if ($makeDir) {
            echo '<br />Successfully created the folder.<br />';
            return true;
        } else {
            echo sprintf('<br /> Sorry, please create the folder manually at: %s/%s', $docRoot, $dirName);
            return false;
        }
    }
}

/**
 * Uploads either a CSV or an EXCEL file to a temporary directory
 *
 * @author  RichardC
 * @param   Resource    $file
 * @return  Boolean     true/false
 */
public function upload( $filename ) {

    $filename = (!isset($filename)) ? $this->file : $filename;

    //Get the document root
    $docRoot = getenv('DOCUMENT_ROOT');

    $this->createDir('uploads');

    if (($_FILES['file']['type'] == 'application/vnd.ms-excel') || ($_FILES['file']['type'] == 'application/csv') || ($_FILES['file']['type'] == 'text/csv') || ($_FILES['file']['type'] == 'text/comma-separated-values') || ($_FILES['file']['type'] == 'application/excel') &&
            ($_FILES["file"]["size"] < 1000000)) {
        if ($_FILES["file"]["error"] > 0) {
            echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
        } else {
            if (file_exists($docRoot . "upload/" . $_FILES["file"]["name"])) {
                echo $_FILES["file"]["name"] . " already exists. ";
                $this->file = $docRoot . '/upload/' . $_FILES["file"]["name"];
            } else {
                move_uploaded_file($_FILES["file"]["tmp_name"], $docRoot . "/upload/" . $_FILES["file"]["name"]);
                $this->file = $docRoot . '/upload/' . $_FILES["file"]["name"];
            }
        }
    } else {
        echo "Invalid file";

        return false;
    }

    //Remove the unwanted file now
    $this->fileContents = file_get_contents($this->file);
    @unlink($this->file);
    unset($this->file);

    return true;
}

如果有人能帮助这一点,它会是多少AP preciated!

If anyone can help on this, it'd be much appreciated!

推荐答案

为了使您的multipart / FORMDATA工作,你必须在你的AJAX请求添加一些额外的东西:

In order to make your multipart/formdata work, you must add some extra stuff in your ajax-request:

cache: false,
contentType: false,
processData: false,

您可以通过这样做很容易地创建自己的数据字段:

You can easily create your data-field by doing this:

var uploadData = $("#uploadFile").prop("files")[0];
var newData = new FormData();

$.each($('#uploadFile').prop("files"), function(i, file) {
    newData.append('file-'+i, file);
});

在您的AJAX请求你必须设定这样的:

in your ajax-request you'll have to set this:

data: newData

这篇关于使用jQuery从通过AJAX一个多/表单数据发送数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆