【问题标题】:submit additional form data jquery file upload提交额外的表单数据jquery文件上传
【发布时间】:2018-04-16 03:10:04
【问题描述】:

我无法在formData 中获取$('.drop').attr('data-id')

$('.drop').fileupload({
    dataType: 'json',
    url: base_path + 'parallax/upload',
    autoUpload: false,
    replaceFileInput: false, // interferes w/ dropify
    formData: {
        id: $('.drop').attr('data-id'), // nothing
        stmt: '1', // works
        '{/literal}{$this->security->get_csrf_token_name()}{literal}': '{/literal}{$this->security->get_csrf_hash()}{literal}'
    },
    add: function (d, c) {
        console.log($(this).attr('data-id')); // works
        console.log($('.drop').attr('data-id')); // works
        console.log($('#fileupload').attr('data-id')); // works
        var a = [];
        var b = /\.(gif|jpe?g|png)$/i;
        if (c.originalFiles[0]['name'].length && !b.test(c.originalFiles[0]['name'])) {
            a.push('Not an accepted file type.');
        }
        if (c.originalFiles[0]['size'].toString().length && c.originalFiles[0]['size'] > maxsize) {
            a.push('Filesize is too big; try increasing post_max_size and/or upload_max_filesize.');
        }
        if (a.length > 0) {
            bootbox.alert(a.join(''));
        } else {
            start_time = new Date().getTime();
            c.submit();
        }
    },

根据docs,可以通过以下方式添加额外的表单数据:

$('#fileupload').fileupload({
    formData: {example: 'test'}
});

这适用于我的 csrf 令牌和我手动定义的其他内容,但是我似乎无法获得 formData 中输入字段的 data-id。没有发生错误,但我确实看到我的请求在没有id 属性的情况下发送 - 如果我手动定义它 - 它可以工作。我也可以在add函数中获取属性。

怎么了?

【问题讨论】:

  • 反对者是否愿意详细说明?

标签: jquery jquery-file-upload form-data


【解决方案1】:

据我所知,您正在尝试在初始化fileuploadclass 时添加$('.drop').attr('data-id') 的值。这时候属性肯定是空的。

尝试在实际上传之前使用fileuploadsubmit 事件设置formaData.id,如下所述: https://github.com/blueimp/jQuery-File-Upload/wiki/How-to-submit-additional-form-data#setting-formdata-on-upload-start

$('.drop').bind('fileuploadsubmit', function (e, data) {
    data.formData.id = $('.drop').attr('data-id');       
    //or in your case `this` will work, too:
    //data.formData.id = $(this).attr('data-id');       
});

【讨论】:

  • 我目前实际上正在这样做,但我想像上面那样尝试它,因为我认为它更干净。为什么那个时候变量不可用?输入在 fileupload 类初始化之前具有该属性,所以我觉得奇怪的是它不能以这种方式添加到 formdata / 访问
  • 恕我直言,事件驱动的解决方案看起来更干净,因为您可以准确地告诉何时收集了属性的值。
  • 但是你能解释一下为什么上面的方法不起作用吗?
  • 不是您提供的代码 sn-p。您是否查看过传输的数据(例如,在 Chrome DevTools/Network 选项卡中)?您能否添加一个<input type="hidden" data-id="youchoose" /> 并在fileupload/formData 中使用它的属性值?只是为了测试?
猜你喜欢
  • 1970-01-01
  • 2011-11-19
  • 2011-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-26
  • 1970-01-01
  • 2013-10-13
相关资源
最近更新 更多