javascript 使用jQuery通过ajax从multipart/form-data发送数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7516381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:22:52  来源:igfitidea点击:

Using jQuery to send data from a multipart/form-data through ajax

phpjavascriptjqueryajaxmultipartform-data

提问by DarkMantis

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

我一整天都在研究这个,但我无法让它发挥作用。

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.

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

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

有人可以请教我如何在没有其他插件的情况下做到这一点(多次上传等)。

Here is my jQuery Code for this bit:

这是我的 jQuery 代码:

function uploadTimesheets(){

函数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();
        }
    }
});

}

}

And here is my PHP upload script:

这是我的 PHP 上传脚本:

    /**
 * 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;
}

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

如果有人可以对此提供帮助,将不胜感激!

回答by Snicksie

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

为了让你的 multipart/formdata 工作,你必须在你的 ajax 请求中添加一些额外的东西:

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

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

在您的ajax请求中,您必须设置:

data: newData