AjaxFileUpload在上传文件后迭代上传的文件

时间:2013-12-20 10:29:18

标签: asp.net ajaxcontroltoolkit asyncfileupload

我在Ajaxcontrol Toolkit中使用AjaxFileUpload控件。

示例代码如下。

<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" ThrobberID="myThrobber" 
AllowedFileTypes="doc,jpg,jpeg,mp3" MaximumNumberOfFiles="10" runat="server"
OnUploadComplete="AjaxFileUpload1_UploadComplete" 
Width="450px" />

<asp:Button ID="btnCheckFiles" Text="CheckFiles" runat="server"/>

我可以将文件保存在AjaxFileUpload1_UploadComplete事件

protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
   AjaxFileUpload1.SaveAs(filepath);
}

上面工作正常,但我没有在UploadComplete事件中保存文件,我想在文件上传后将它们保存在另一个按钮的Button Click事件中,这里说btnCheckFiles的点击事件,如下所示

protected void btnCheckFiles_Click(object sender, EventArgs e)
{
  // Iterate all files here uploaded 
  // for each file in ajaxfileupload control
  //iterate and save each file to a path
}

有没有办法达到上述要求?

1 个答案:

答案 0 :(得分:2)

在您的aspx页面中进行如下更改:

<asp:HiddenField id="hdnFileIDs" runat="server" Value="" />

<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" ThrobberID="myThrobber" 
AllowedFileTypes="doc,jpg,jpeg,mp3" MaximumNumberOfFiles="10" runat="server"
OnUploadComplete="AjaxFileUpload1_UploadComplete" 
OnClientUploadComplete="onClientUploadComplete"
Width="450px" />

添加javascript块如下:

 <script type="text/javascript">    
function onClientUploadComplete(sender, e) {
                var id = e.get_fileId();
                var objHdnFileIDs = document.getElementById('<%=hdnFileIDs.ClientID%>');
                objHdnFileIDs.value = objHdnFileIDs.value + id + ',';
               }
</script>

在你的.cs页面

  protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs file)
    {
         Session["fileContents_" + file.FileId] = file.GetContents();
         Session["fileExtension_" + file.FileId] = file.FileName.Substring(file.FileName.LastIndexOf('.'));
       //AjaxFileUpload1.SaveAs(filepath);
    }

protected void btnCheckFiles_Click(object sender, EventArgs e)
{
  // Iterate all files here uploaded 
   if (!string.IsNullOrEmpty(hdnFileIDs.Value))
        {
            string strFileIDs = hdnFileIDs.Value;
            string[] arrFileIDs = strFileIDs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (arrFileIDs != null && arrFileIDs.Length > 0)
            {
                foreach (string strFileID in arrFileIDs)
                {
                    var fileContents = (byte[])Session["fileContents_" + strFileID];
                    var fileExtension = (string)Session["fileExtension_" + strFileID];

                    File.WriteAllBytes(filepath + strFileID + fileExtension, fileContents);
                    Session.Remove("fileContents_" + strFileID);
                    Session.Remove("fileExtension_" + strFileID);
                }
            }
        }
 }