简体   繁体   English

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

[英]how can I reset a blueimp jQuery fileupload plugin?

The gist: how can I reset a blueimp jQuery fileupload plugin so that it thinks no files have been uploaded already?要点:如何重置 blueimp jQuery fileupload 插件,使其认为尚未上传任何文件?

My Scenario我的场景

  • I have an upload form that only allows one file to be uploaded.我有一个只允许上传一个文件的上传表单。
  • Once that file is uploaded, it is analyzed.一旦该文件被上传,就会对其进行分析。 At this point, the user has the option to click a "cancel" button, where I reset the rest of my viewmodel.此时,用户可以选择单击“取消”按钮,在那里我重置视图模型的其余部分。
  • When the user clicks cancel, I would like to reset the count of files the user has uploaded, because they're essentially starting fresh.当用户点击取消时,我想重置用户上传的文件数,因为它们基本上是重新开始的。
  • I still want the one file maximum to apply after reset.我仍然希望在重置后最多应用一个文件。

What happens currently目前发生了什么

  • Upload a file上传一个文件
  • Click the cancel button, everything resets (ie I re-initialize the file upload control)点击取消按钮,一切重置(即我重新初始化文件上传控件)
  • Attempt to upload a file and am still told the number of max files has been reached.尝试上传文件,但仍被告知已达到最大文件数。

What I've Tried我试过的

I tried calling fileupload('destroy') and then reinitializing, but that appeared to have no result (I was hoping that destroying would also tear down the tracking of the instance).我尝试调用 fileupload('destroy') 然后重新初始化,但这似乎没有结果(我希望销毁也会破坏实例的跟踪)。

My question(s):我的问题:

  • What is the best way to destroy/re-initialize/reset the upload control as if it's being started from scratch?销毁/重新初始化/重置上传控件的最佳方法是什么,就好像它是从头开始一样?
  • If there is none, is there any way to programmatically make blueimp think that zero files have been uploaded after one already has, to effectively reset it?如果没有,有没有办法以编程方式让 blueimp 认为已经上传了零个文件,以有效地重置它? Thanks in advance for any help you can give!在此先感谢您提供的任何帮助!

A note on version:版本说明:

FYI, I am on v8.8.1 -- I would prefer not to upgrade because a colleague changed some of the code in a specific way -- ugh.仅供参考,我使用的是 v8.8.1——我不想升级,因为一位同事以特定方式更改了一些代码——呃。 We plan to remove this customization and upgrade but at a scheduled date.我们计划在预定日期删除此自定义和升级。 If I have to update to resolve this, feel free to let me know because that's completely fair.如果我必须更新以解决此问题,请随时告诉我,因为这完全公平。

Update: Some Code更新:一些代码

The first file upload control on the page:页面第一个文件上传控件:

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

The second file upload control on the page:页面上的第二个文件上传控件:

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

I'm able to clear the first control using:我可以使用以下方法清除第一个控件:

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

presumably because the file has already been uploaded at that point (which is fine).大概是因为文件已经在那时上传了(这很好)。

However, this doesn't work for the second form.但是,这不适用于第二种形式。 I have tried:我试过了:

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

This makes the items disappear from the page, but they reappear when an additional file is added.这会使项目从页面上消失,但在添加其他文件时它们会重新出现。

I have also tried $("#detailsFileUploadForm").fileupload('destroy') with no success (presumably because it does not handle these functions and is more about bindings.我也试过$("#detailsFileUploadForm").fileupload('destroy')没有成功(大概是因为它不处理这些功能,更多的是关于绑定。

The answer to this was a lot simpler than I expected:这个问题的答案比我预期的要简单得多:

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

Previously, I think I was doing too much -- attempting to destroy/reset the container didn't work as well.以前,我认为我做得太多了——尝试销毁/重置容器并没有奏效。

With this one line of code, the lists appear to reset and all is working well as far as I can tell.使用这一行代码,列表似乎重置了,据我所知,一切都运行良好。

here is an ideal solution to reset jquery-fileupload这是重置 jquery-fileupload 的理想解决方案

in the file "main.js" just delete or comment Load existing file script like this:在文件“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});
       });
 * /}

so you have to either clear or comment on the part "// Load existing files"所以你必须清除或评论“//加载现有文件”部分

I had a similar problem where previously uploaded files were included in the next upload.我有一个类似的问题,以前上传的文件包含在下一次上传中。 Just like you been struggling for hours.就像你挣扎了几个小时一样。 Until I tried the following solution.直到我尝试了以下解决方案。 This will do the trick to clear the previously uploaded files.这将清除以前上传的文件。

On Add Function just add "change" event of the file input element like below:在添加函数上,只需添加文件输入元素的“更改”事件,如下所示:

$('#YourFileUploadElementId').change(function(e) {
     data.files.splice(0); // Clear All Existing Files
});

Full Example Below:完整示例如下:

$('#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
 });

Note: Just change the YourFileUploadElementId to your file upload element id.注意:只需将YourFileUploadElementId更改为您的文件上传元素 ID。 Don't forget to filter the files during upload with the following:不要忘记在上传过程中使用以下内容过滤文件:

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

Here is the complete example on jsfiddle.net这是 jsfiddle.net 上的完整示例

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 隐藏(不删除)Blueimp jquery fileupload插件中的复选框 - Hide(not delete) the checkbox in Blueimp jquery fileupload plugin Blueimp插件文件上传Jquery:向PHP处理程序发送其他信息 - Blueimp plugin fileupload Jquery: Send additional information to PHP handler 如何抑制FedAuth cookie通过Blueimp Fileupload上传? - How can I suppress FedAuth cookies from being uploaded with Blueimp Fileupload? AJAX输入上的jQuery Fileupload Blueimp - jQuery Fileupload Blueimp on AJAX input 如何获取BlueImp jQuery FileUpload以生成唯一的文件名 - How to get BlueImp jQuery FileUpload to generate unique filenames 如何使用 jQuery 选择的插件重置表单? - How can I reset a form with jQuery chosen plugin? 如何在Blueimp jquery文件上传器中发送会话数据? - How can send I session data in the Blueimp jquery file uploader? 如何在blueimp jquery下载程序中过滤要下载的文件 - how can I filter the files for download in the blueimp jquery download program jQuery Blueimp fileupload插件删除文件而不需要先检查复选框? - jQuery Blueimp fileupload plugin delete files without requiring checking checkbox first? 带有AngularJS和Spring MVC的jQuery Fileupload(Blueimp) - jQuery Fileupload (Blueimp) with AngularJS and Spring MVC
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM