Jquery文件上传:如何设置多个文件上传小部件?

时间:2015-07-23 12:44:11

标签: jquery django jquery-file-upload blueimp

我正在使用Jquery File Upload插件和Django作为后端。一切顺利,直到我尝试整合Multiple File Upload Widgets on the same page

第一个问题

首先,我不确定除了文档之外我应该改变什么。页面中提到Here is the original main.js file。我不是jQuery专家,我无法理解我需要改变的内容。

我很高兴看到这个main.js的一个例子被重写了。

第二个问题

在我的一个页面上拥有多个小部件的全部目的是显示不同的元素。 这就是为什么在我的后端,upload/view/网址变为upload/view/(?P<pk>\d+)/

例如,如果在一个页面中我想要显示包含许多照片的两张相册,我希望我的页面可以调用upload/view/1upload/view/2

后端部分工作正常,因为调用urls会返回正确的json答案。

但对于ajax部分,我不知道该怎么做。在main.js文件中,我可以看到它应该在哪里更改,但不知道如何操作:

            $.ajax({
            // Uncomment the following to send cross-domain cookies:
            //xhrFields: {withCredentials: true},
            //url: $('#fileupload').fileupload('option', 'url'),
            url: '/upload/view/',
            dataType: 'json',
            context: $('#fileupload')[0]

任何帮助将不胜感激。感谢。

2 个答案:

答案 0 :(得分:0)

您需要评论或删除这部分代码:

// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
    // Uncomment the following to send cross-domain cookies:
    //xhrFields: {withCredentials: true},
    //url: 'server/php/'
});

// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
    'option',
    'redirect',
    window.location.href.replace(
        /\/[^\/]*$/,
        '/cors/result.html?%s'
    )
);

并设置这一行,允许您根据fileupload类设置多个上传小部件:

$('.fileupload').each(function () {
  $(this).fileupload({
    dropZone: $(this)
  });
});

答案 1 :(得分:0)

好的,

基于@Hackerman的答案和其他的脑筋,这里是最后工作的main.js文件:

$(function () {
    'use strict';

    // cpt will count (0-based) number of fileupload forms in the page
    var cpt = 0;

    $('.fileupload').each(function () {

        $(this).fileupload({
          dropZone: $(this)
        });

        // Load existing files:
        $(this).addClass('fileupload-processing');
        $.ajax({
            url: '/upload/view/' + $(this).children("input[name='folder_element']").val(),
            dataType: 'json',
            context: $('.fileupload')[cpt] // select the right form
        }).always(function () {
            $(this).removeClass('fileupload-processing');
        }).done(function (result) {
            $(this).fileupload('option', 'done')
                .call(this, null, {result: result});
        });

        cpt += 1;

    });

});

以及与2种形式相对应的HTML:

<form class="fileupload" method="post" action="." enctype="multipart/form-data">
  <input type="hidden" name="folder_element" value="1">
  ...
</form>

<form class="fileupload" method="post" action="." enctype="multipart/form-data">
  <input type="hidden" name="folder_element" value="2">
  ...
</form>

我不是jQuery专家,但似乎你需要有一个count变量来传递ajax请求中的良好上下文。

相关问题