how can I reset a blueimp jQuery fileupload plugin?
Asked Answered
O

3

16

The gist: how can I reset a blueimp jQuery fileupload plugin so that it thinks no files have been uploaded already?

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 (i.e. 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).

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

Ogletree answered 17/1, 2014 at 13:53 Comment(7)
Do you use it's ui widget? It checks the number of the appended elements, each element stores the selected file in it's own dataset.Anaplastic
@BlackSheep thanks for the response! This sounds like it could definitely be on the right track. When you say appended elements, where exactly do you mean? Would it be enough to remove the row for the file from the table that is the upload template?Ogletree
I had used the plugin for an app several months ago, as far as I can remember removing children of the fileContainer will remove all the selected files.Anaplastic
.data('data'); of each element refers to the selected file.Anaplastic
Just to confirm, when you say "fileContainer", you mean the element I initially call fileupload() on?Ogletree
IMO you could just use a simple boolian variable and set it on true by default, false on done and again true on reset.Wartime
Hi all, FYI I added some code and explanation. @Dirty-flow, not sure what you mean. I have a max of one file, and the problem is that when I reset the form, I can't then add another file (because it says max has already been uploaded). I fixed that on my summary form by removing the table element, but it doesn't appear to work for the second form. Not sure how introducing a bool would help my problem here but am open to it with more explanation.Ogletree
O
19

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.

Ogletree answered 23/1, 2014 at 15:38 Comment(5)
I want to clear the selected files after successfully uploaded them, will $("table tbody.files").empty(); be engough?Beet
Allan, my guess is it would be. However, if you're just looking to clear them from the display, you can simply make the after upload template empty, which means uploaded files won't show. To me, that's easiestOgletree
@SeanKillen no... what I want is the same as yours, I want to clear it's upload-queue, which have result in user sending the previously selected filesBeet
@AllanRuin in that case, yes, I believe it will work. However, I'm not convinced it's the best way. There may just be some sort of programmatic way of removing the files when it's done (perhaps subscribing to one of the events thrown and taking action based upon it). However, this has been working for me as a quick & dirty solution.Ogletree
need to diffrenct forms on same page and upload files like multiple uploader.Is this possible ?Labdanum
E
1

here is an ideal solution to reset jquery-fileupload

in the file "main.js" just delete or comment Load existing file script like this:

 

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"

Encephalo answered 21/10, 2018 at 19:20 Comment(0)
O
0

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

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

Octagon answered 25/3, 2020 at 11:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.