【问题标题】:Using jQuery to send data from a multipart/form-data through ajax使用 jQuery 通过 ajax 从 multipart/form-data 发送数据
【发布时间】:2011-09-22 14:24:01
【问题描述】:

我已经为此工作了一整天了,但我就是无法让它工作。

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

我的文件上传脚本正在等待文件名作为参数(也尝试过),但它只是不想从文件输入框本身获取数据。

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

这是我的 jQuery 代码:

函数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 上传脚本:

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

如果有人能提供帮助,将不胜感激!

【问题讨论】:

  • 我不确定这是否允许文件字段......但是,有一个 JQuery 插件可以处理提交带有文件的表单:jquery.malsup.com/form。另一种选择是使用文件上传插件,如uploadify.com

标签: php javascript jquery ajax multipartform-data


【解决方案1】:

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

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

您可以通过以下方式轻松创建数据字段:

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

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

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

data: newData

【讨论】:

  • 它目前仍然无法正常工作,但我会继续尝试,看看我能做到什么。再次感谢队友!
  • 我相信这个解决方案只适用于IE10+(不适用于IE9及以下)
猜你喜欢
  • 2012-10-01
  • 1970-01-01
  • 2011-08-21
  • 1970-01-01
  • 1970-01-01
  • 2013-04-09
  • 2021-01-07
  • 2021-12-09
相关资源
最近更新 更多