Clear up AjaxToolkit AsyncFileUpload control

2019-06-20 15:54发布

问题:

I am using an AsyncFileUpload control in my aspx.net page. This control is running inside an update panel.

I can successfully upload files to the server asynchronously.

My problem is that I can't refresh the entire page after each file is uploaded, so I need to figure out how to clear up the last uploaded file, so when the user selects a new file to upload, the old file does not appear in the control and the control does not keep its last upload in ViewState.

I have tried this http://www.aspsnippets.com/Articles/Clear-contents-of-AsyncFileUpload-Control-after-upload-and-page-revisit.aspx but it only clears up the html, when I do the server async postback, the AsyncFileUpload control still has the last file uploaded.

Is there a way to do the clean up at server side? Perhaps anything related to view state?

Any help would be appreciated, Thank you.

回答1:

On the client side you can use OnClientUploadComplete event to clear up the last uploaded file entry. Once the file uploading is completed and when the postback occurs the AsyncFileUpload1.HasFile will return false.

In aspx page:

<asp:AsyncFileUpload ID="AsyncFileUpload1" OnClientUploadComplete="success" OnUploadedComplete="AsyncFileUpload1_UploadedComplete" runat="server" />

and inside JavaScript tags:

function success() {         
    var fu = document.getElementById("AsyncFileUpload1"); 
    document.getElementById("AsyncFileUpload1").innerHTML = fu.innerHTML; 
} 


回答2:

This worked for me :

function ClearFile() {
    $('input[type="file"]').each(function () {
        $("#" + this.id).replaceWith($("#" + this.id).clone(true));
    });

    //For other browsers
    $('input[type="file"]').each(function () { $("#" + this.id).val(""); });
}


回答3:

Server side clearing worked for me :

protected void FileUploadComplete(object sender, EventArgs e) 
{
    string filename = System.IO.Path.GetFileName(AsyncFileUpload1.FileName);
    AsyncFileUpload1.PostedFile.SaveAs(Server.MapPath("Uploads/") + filename);

    ClearContents(sender as Control);
}

private void ClearContents(Control control)
{
   for (var i = 0; i < Session.Keys.Count; i++)
   {
      if (Session.Keys[i].Contains(control.ClientID))
      {
         Session.Remove(Session.Keys[i]);
         break;
      }
   }
}

reference: link in the question by Fer. http://www.aspsnippets.com/Articles/Clear-contents-of-AsyncFileUpload-Control-after-upload-and-page-revisit.aspx



回答4:

<asp:AsyncFileUpload ID="AsyncFileUpload1" OnClientUploadComplete="success" OnUploadedComplete="AsyncFileUpload1_UploadedComplete" runat="server" />

and

function success(sender, args) { $(sender._element).find('input').val(''); }

that one works perfectl on all modern browsers, thanks to "Scotty.NET"