如何重置blueimp jQuery文件上传插件?

16
要点:如何重置blueimp jQuery fileupload插件,使其认为没有文件已上传?

我的场景

  • 我有一个上传表单,只允许上传一个文件。
  • 一旦上传了该文件,它就会被分析。此时,用户可以点击“取消”按钮,我将重置我的ViewModel的其余部分。
  • 当用户点击取消时,我希望重置用户已上传的文件数,因为他们从本质上来说是重新开始的。
  • 在重置后仍然希望最多只能上传一个文件。

当前发生的情况

  • 上传一个文件
  • 点击取消按钮,一切都重置了(即我重新初始化了文件上传控件)
  • 尝试上传文件,仍然被告知已达到最大文件数。

我尝试过的方法

我尝试调用fileupload('destroy')然后重新初始化,但是似乎没有任何效果(我希望销毁也会拆除实例跟踪)。

我的问题:

  • 销毁/重新初始化/重置上传控件的最佳方法是什么?
  • 如果没有,是否有办法通过编程使blueimp认为已上传零个文件,以有效地重置它? 非常感谢你能给出的任何帮助!

版本说明:

我使用的版本是v8.8.1 -- 我不想升级,因为同事以特定方式更改了一些代码--呃。我们计划删除这个自定义并升级,但在预定日期。如果必须更新以解决此问题,请随时让我知道,因为这是完全公平的。

更新:一些代码

页面上的第一个文件上传控件:

<form id="summaryFileUploadForm" action="/api/InvoiceDetailsFile/PostForProcessing" method="POST"
    enctype="multipart/form-data" data-bind="disableFileUpload: InvoiceHasSummaryDocument() || (!InvoiceDataIsFilledIn())">

    <div class="fileupload-buttonbar">
        <div class="fileupload-buttons">

            <!-- The fileinput-button span is used to style the file input field as button -->
            <span class="fileinput-button">
                <span>Add files...</span>
                <input id="file" type="file" name="file" />
            </span>

            <span class="fileupload-loading"></span>
        </div>
        <!-- The global progress information -->
        <div class="fileupload-progress fade" style="display: none">
            <!-- The global progress bar -->
            <div class="progress" role="progressbar" aria-valuemin="0" aria-valuemax="100"></div>
            <!-- The extended global progress information -->
            <div class="progress-extended">&nbsp;</div>
        </div>
    </div>
    <div data-bind="fadeVisible: InvoiceHasSummaryDocument()">
        <span class="ui-icon ui-icon-check float-left"></span><span>A summary document has been uploaded.</span>
    </div>
    <span data-bind="fadeVisible: (!InvoiceDataIsFilledIn())">Please fill out invoice information before uploading a file.</span>
    <!-- The table listing the files available for upload/download -->
    <table role="presentation">
        <tbody class="files" id="Tbody1"></tbody>
    </table>

    <script id="summaryFileDownloadTemplate" type="text/x-tmpl">

    </script>
</form>

页面上的第二个文件上传控件:

<form id="detailsFileUploadForm" action="/api/InvoiceDetailsFile/PostForProcessing" method="POST"
    enctype="multipart/form-data" data-bind="disableFileUpload: Invoice().DetailItems().length > 0 || (!InvoiceHasSummaryDocument())">

    <div class="fileupload-buttonbar">
        <div class="fileupload-buttons">

            <!-- The fileinput-button span is used to style the file input field as button -->
            <span class="fileinput-button">
                <span>Add files...</span>
                <input id="file" type="file" name="file" />
            </span>

            <span class="fileupload-loading"></span>
        </div>
        <!-- The global progress information -->
        <div class="fileupload-progress fade" style="display: none">
            <!-- The global progress bar -->
            <div class="progress" role="progressbar" aria-valuemin="0" aria-valuemax="100"></div>
            <!-- The extended global progress information -->
            <div class="progress-extended">&nbsp;</div>
        </div>
    </div>
    <span><strong>NOTE: </strong>Only Excel 2007+ (.xlsx) files are accepted. <a href="<%= ResolveUrl("~/asset/xlsx/Ligado_InvoiceUploadTemplate_Standard.xlsx") %>" target="_blank" id="A1">Need a blank Invoice Upload template?</a><br />
    </span>
    <span data-bind="fadeVisible: Invoice().DetailItems().length > 0">Invoice details have been uploaded.</span>
    <span data-bind="fadeVisible: (!InvoiceHasSummaryDocument())">Please upload a summary file prior to uploading a details file.</span>

    <!-- The table listing the files available for upload/download -->
    <table role="presentation">
        <tbody class="files" id="fileList"></tbody>
    </table>
    <script id="template-upload" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
    <tr class="template-upload fade" style="display:none">
        <td>
            <span class="preview"></span>
        </td>
        <td>
            <p class="name">{%=file.name%}</p>
            {% if (file.error) { %}
                <div><span class="error">Error:</span> {%=file.error%}</div>
            {% } %}
        </td>
        <td>
            <p class="size">{%=o.formatFileSize(file.size)%}</p>
            {% if (!o.files.error) { %}
                <div class="progress" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"></div>
            {% } %}
        </td>
        <td>
            {% if (!o.files.error && !i && !o.options.autoUpload) { %}
                <button class="start">Start</button>
            {% } %}
            {% if (!i) { %}
                <button class="cancel">Cancel</button>
            {% } %}
        </td>
    </tr>
{% } %}
    </script>

    <script id="template-download" type="text/x-tmpl">

    </script>
</form>

我可以通过以下方式清除第一个控件:

    $("tbody.files").empty();

可能是因为该文件在那个时候已经上传了(这没问题)。

但是,对于第二个表单,这种方法行不通。我尝试过:

    $("#detailsFileUploadForm").find('.cancel').click();

这使得页面上的项目消失了,但是当添加另一个文件时,它们会重新出现。

我还尝试了$("#detailsFileUploadForm").fileupload('destroy'),但没有成功(可能是因为它不能处理这些功能,而更多地是关于绑定)。


你使用它的UI小部件吗?它会检查附加元素的数量,每个元素都将所选文件存储在自己的数据集中。 - Ram
@BlackSheep 感谢您的回复!这听起来肯定是正确的方向。当您说追加元素时,您指的是哪里?仅从上传模板表中删除文件行是否足够? - SeanKilleen
每个元素的.data('data')指的是所选文件。 - Ram
只是确认一下,当你说“fileContainer”时,你是指我最初调用fileupload()的元素吗? - SeanKilleen
在我看来,你可以使用一个简单的布尔变量,默认设置为true,在完成时设置为false,重置后再次设置为true。 - Dirty-flow
显示剩余2条评论
3个回答

19

答案比我预期的要简单得多:

$("table tbody.files").empty();

之前,我认为我做得太多了——试图销毁/重置容器并没有很好地发挥作用。

有了这一行代码,列表似乎已经重置了,据我所知,目前一切都运转良好。


我想在成功上传所选文件后清除它们,$("table tbody.files").empty(); 足够吗? - Allan Ruin
艾伦,我猜应该是这样的。但是,如果你只是想从显示中清除它们,你可以简单地使上传后模板为空,这意味着已上传的文件不会显示。对我来说,这是最简单的方法。 - SeanKilleen
@SeanKillen 不是...我想要的和你一样,我想要清除它的上传队列,这导致用户发送之前选择的文件。 - Allan Ruin
@AllanRuin 如果是这样的话,我相信它会起作用。但是,我并不认为这是最好的方法。也许有一些编程方式可以在完成时删除文件(例如订阅其中一个事件并根据其采取行动)。然而,这对我来说已经是一个快速而简单的解决方案了。 - SeanKilleen
需要在同一页上使用不同的表单并上传文件,就像多文件上传器一样。这是否可行? - Coder

1

这里有一个重置jquery-fileupload的理想解决方案。

在文件"main.js"中,只需删除或注释掉类似于“加载现有文件”的脚本,如下所示:

 

if (window.location.hostname === 'blueimp.github.io') {
        // Demo settings:
        $ ('# fileupload'). fileupload ('option', {
            url: '//jquery-file-upload.appspot.com/',
            // Enable image resizing, except for Android and Opera,
            // which actually support image resizing, but fail to
            // send Blob objects via XHR requests:
            disableImageResize: /Android(?!.*Chrome)|Opera/
                .test (window.navigator.userAgent)
            maxFileSize: 999000,
            acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
        });
        // Upload server status check for browsers with CORS support:
        if ($ .support.cors) {
            $ .Ajax ({
                url: '//jquery-file-upload.appspot.com/',
                type: 'HEAD'
            }). fail (function () {
                $ ('<div class = "alert alert-danger" />')
                    .text ('Upload server currently unavailable -' +
                            new Date ())
                    .appendTo ( '# fileupload');
            });
        }
      } else {
        // Load existing files:
 / * $ ('# fileupload'). addClass ('fileupload-processing');
        $ .Ajax ({
            // Uncomment the following to send cross-domain cookies:
            // xhrFields: {withCredentials: true},
            url: $ ('# fileupload'). fileupload ('option', 'url')
           dataType: 'json',
           context: $ ('# fileupload') [0]
       }). always (function () {
           $ (This) .removeClass ( 'fileupload-processing');
       }). done (function (result) {
          $ (this) .fileupload ('option', 'done')
                .call (this, $ .Event ('done'), {result: result});
       });
 * /}

所以你需要清除或者注释掉 "// Load existing files" 这一部分


0
我曾经遇到过类似的问题,之前上传的文件会被包含在下一次上传中。就像你一样,我也为此苦苦挣扎了数小时。直到我尝试了以下解决方案。
这个方法可以清除之前上传的文件。
在添加功能时,只需像下面这样添加文件输入元素的“change”事件即可:
$('#YourFileUploadElementId').change(function(e) {
     data.files.splice(0); // Clear All Existing Files
});

完整示例如下:

$('#YourFileUploadElementId').fileupload({
    // Some options
    add: function (e, data) {
        if(data.files.length > 0) {
          // Upload Code Here
        }
        $('#YourFileUploadElementId').change(function(e) {
          data.files.splice(0); // Clear All Existing Files
        });
    },
    // Other Events
 });

注意:只需将YourFileUploadElementId更改为您的文件上传元素ID即可。 上传期间不要忘记使用以下内容过滤文件:

if(data.files.length > 0) {
 // Upload Code Here
}

这是在 jsfiddle.net 上的完整示例

http://jsfiddle.net/dustapplication/cjodz2ma/5/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接