AjaxControlToolkit AsyncFileUpload - how to modify

2019-08-21 17:04发布

问题:

I am trying to set a label text value after a file is uploaded to the server using a AsyncFileUpload component in AjaxControlToolkit. But it seams it is ineffective, although the file uploader is green after the upload, and the upload works.

protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
    string filename  = System.IO.Path.GetFileName(AsyncFileUpload1.FileName);
    AsyncFileUpload1.SaveAs(Server.MapPath("Uploads/") + filename); 
    sourceLabel.Text="saved to "+filename; //this has no effect. I assume this is because the event is Async, but how can I set the value of  sourceLabel?
}

回答1:

The AsyncFileUpload control uses hidden frame for file submitting so all updates of controls will be lost. Check this link and draw attention how the uploadResult label's text changed from AsyncFileUpload1_UploadedComplete method: Ajax Control Toolkit source code



回答2:

It works for me: https://stackoverflow.com/a/12472235/2247978

.....................................................................................................

Add HiddenField control onto a form:

<asp:HiddenField runat="server" ID="UploadedPathHiddenField" />

Rewrite UploadComplete method as below:

protected void UploadComplete(object sender, AsyncFileUploadEventArgs e)
{
    var fileName = GeneratePrefixFileName() +  System.IO.Path.GetFileName(e.FileName);
    var relativePath = "~/Image/" + fileName;
    var filePath = Server.MapPath(relativePath);
    AsyncFileUpload1.SaveAs(filePath);
    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "filePath", "top.$get(\"" + UploadedPathHiddenField.ClientID + "\").value = '" + ResolveClientUrl(relativePath) + "';", true);
}

After that you can get path of saved image in showConfirmation method by :

var src = $get("<%= UploadedPathHiddenField.ClientID %>").value;

.....................................................................................................

protected void BtnUpload_Click(object sender, EventArgs e)
{
    UploadMessage.Text = UploadedPathHiddenField.Value;
}