麓谷官网欢迎你访问长沙北大青鸟麓谷校区,支持你成为一个受人尊重的专业人才!
当前位置: 首页 > 青鸟知识 > net

asp.net中如何实现多个文件同时下载

来源:长沙北大青鸟|发布时间:2017-04-06|浏览量:

学IT,好工作

就读长沙岳麓职业培训学校

求学热线: 400-160-2868

  如何实现asp.net多个文件同时下载?先要读取文件夹下的文件,可能同时存在多个文件;然后选中文件,然后点击下载,同时可以选择多个文件。通过生产压缩包的形式进行下载,然后再清除压缩包,这样用户可以一次性全部下载下来。

  一、获取目录下的所有文件,然后绑定到checkboxlist中 ,代码如下:

ckl_ck.Items.Clear();
DirectoryInfo TheFolder = new DirectoryInfo(Server.MapPath("Resource/Help"));
//遍历文件夹下的文件
foreach (FileInfo NextFile in TheFolder.GetFiles())

  二、选中文件后,点击下载按钮。代码:

 protected void Btn_down_Click(object sender, EventArgs e)
{
if (ckl_ck.Items.Count > 0)
{
 List<string> listFJ = new List<string>();//保存附件路径
 List<string> listFJName = new List<string>();//保存附件名字
 for (int i = 0; i < ckl_ck.Items.Count; i++)
 {
 if (ckl_ck.Items[i].Selected)
 {
  listFJ.Add(Server.MapPath("Resource/Help/") + ckl_ck.Items[i].Text);
  listFJName.Add(ckl_ck.Items[i].Text);
 }
 
 }
 string time = DateTime.Now.Ticks.ToString();
 ZipFileMain(listFJ.ToArray(), listFJName.ToArray(), Server.MapPath("Resource/Help/" + time + ".zip"), 9);//压缩文件
 DownloadFile(Server.UrlEncode("附件.zip"), Server.MapPath("Resource/Help/" + time + ".zip"));//下载文件
}
}
private void DownloadFile(string fileName, string filePath)
{
FileInfo fileInfo = new FileInfo(filePath);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.AddHeader("Content-Transfer-Encoding", "binary");
Response.ContentType = "application/octet-stream";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
Response.WriteFile(fileInfo.FullName);
Response.Flush();
File.Delete(filePath);//删除已下载文件
Response.End();
}
 
/// <summary>
/// 压缩文件
/// </summary>
/// <param name="fileName">要压缩的所有文件(完全路径)</param>
/// <param name="fileName">文件名称</param>
/// <param name="name">压缩后文件路径</param>
/// <param name="Level">压缩级别</param>
public void ZipFileMain(string[] filenames, string[] fileName, string name, int Level)
{
ZipOutputStream s = new ZipOutputStream(File.Create(name));
Crc32 crc = new Crc32();
//压缩级别
s.SetLevel(Level); // 0 - store only to 9 - means best compression
try
{
 int m = 0;
 foreach (string file in filenames)
 {
 //打开压缩文件
 FileStream fs = File.OpenRead(file);//文件地址
 byte[] buffer = new byte[fs.Length];
 fs.Read(buffer, 0, buffer.Length);
 //建立压缩实体
 ZipEntry entry = new ZipEntry(fileName[m].ToString());//原文件名
 //时间
 entry.DateTime = DateTime.Now;
 //空间大小
 entry.Size = fs.Length;
 fs.Close();
 crc.Reset();
 crc.Update(buffer);
 entry.Crc = crc.Value;
 s.PutNextEntry(entry);
 s.Write(buffer, 0, buffer.Length);
 m++;
 }
}
catch
{
 throw;
}
finally
{
 s.Finish();
 s.Close();
}
}

   三、系统中需要引用的dll 需要下载。

  引用文件dll:ICSharpCode.SharpZipLib.dll

  1. 合成下载文件夹

   Protected Sub btn_down_click(ByVal sender As Object, ByVal e As EventArgs) Handles btn_Down.Click
        If txtBz.Text.Trim = "" Then
            Page.ClientScript.RegisterClientScriptBlock(Me.[GetType](), "", "alert('请填写下载备注!');", True)
            Exit Sub
        End If

        Dim i As Integer
        Dim selcount As Integer = 0
        Dim fileList As List(Of String) = New List(Of String)()
        If rptList.Items.Count > 0 Then
            For i = 0 To rptList.Items.Count - 1
                Dim chk As CheckBox = rptList.Items(i).FindControl("cbkItem")
                If chk IsNot Nothing AndAlso chk.Checked Then
                    selcount += 1
                    Dim filePath As HiddenField = rptList.Items(i).FindControl("hfUrl")
                    Dim fileName As HiddenField = rptList.Items(i).FindControl("hfFileName")

                    If filePath IsNot Nothing Then
                        Dim root As String = Request.PhysicalApplicationPath
                        Dim tmpUrl = root + filePath.Value
                        fileList.Add(tmpUrl + "|" + fileName.Value) '最后结果为:路径|名称
                    End If
                End If

            Next
        End If
        Dim time As String = DateTime.Now.Ticks.ToString()
        Dim baseFolder As String = HttpContext.Current.Request.MapPath("~/UploadFile/TempWorkFlow/")
        If Not Directory.Exists(baseFolder) Then
            Directory.CreateDirectory(baseFolder)
        End If
        If selcount = 0 Then
            Page.ClientScript.RegisterClientScriptBlock(Me.[GetType](), "", "alert('请选择要下载的文件!');", True)
            Exit Sub
        Else
            ZipFileMain(fileList.ToArray(), baseFolder & time & ".zip", 9)
            '压缩文件
            DownloadFile(Server.UrlEncode("附件.zip"), baseFolder & time & ".zip")
            'Response.Redirect("Download.aspx?FileName=" & Server.UrlEncode("附件.zip") & "&FilePath=" & baseFolder & time & ".zip")
        End If
    End Sub

   2. 压缩下载函数

    ''' <summary>
    ''' 压缩文件
    ''' </summary>
    ''' <param name="fileName">要压缩的所有文件(完全路径)</param>
    ''' <param name="name">压缩后文件路径</param>
    ''' <param name="Level">压缩级别</param>
    Public Shared Sub ZipFileMain(filenames As String(), name As String, Level As Integer)
        Dim s As New ZipOutputStream(File.Create(name))
        Dim crc As New Crc32()
        '压缩级别
        s.SetLevel(Level)
        ' 0 - store only to 9 - means best compression
        Try
            For Each file__1 As String In filenames
                '打开压缩文件
                Dim fs As FileStream = File.OpenRead(file__1.Split("|"c)(0))
                '文件地址
                Dim buffer As Byte() = New Byte(fs.Length - 1) {}
                fs.Read(buffer, 0, buffer.Length)

                '建立压缩实体
                Dim entry As New ZipEntry(file__1.Split("|"c)(1))
                '原文件名
                '时间
                entry.DateTime = DateTime.Now
                '空间大小
                entry.Size = fs.Length
                fs.Close()
                crc.Reset()
                crc.Update(buffer)
                entry.Crc = crc.Value
                s.PutNextEntry(entry)
                s.Write(buffer, 0, buffer.Length)
            Next
        Catch
            'Throw
        Finally
            s.Finish()
            s.Close()
        End Try
    End Sub

   3. 压缩下载函数

   <table class="table table-hover table-bordered table-striped">
            <thead>
                <tr>
                   <th>
                            <input id="cbkAll" type="checkbox" onclick="checkAll();" />选择
                        </th>
                        <th width="20%">文件编号
                        </th>  
                        <th>文件名称
                        </th>
                        <th>文件大小
                        </th>
                        <th>分类
                        </th>
                         <th>文件夹名
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <asp:Repeater ID="rptList" runat="server" >    
                        <ItemTemplate>
                            <tr>
                                <td class="style2">
                                    <asp:CheckBox runat="server" ID="cbkItem" />
                                    <asp:HiddenField ID="hfID" runat="server" Value='<%#Eval("FileID").ToString()%>' />
                                     <asp:HiddenField ID="hfUrl" runat="server" Value='<%#Eval("FilePath").ToString()%>' />
                                      <asp:HiddenField ID="hfFileName" runat="server" Value='<%#Eval("FileName").ToString()%>' />
                                </td>
                                <td>
                                    <%#Eval("FileID").ToString()%>
                                </td>                                
                                <td>
                                   <%#Eval("FileName").ToString()%>
                                </td>
                                <td align="center">
                                     <%#Eval("FileSize").ToString()%>
                                </td>
                                <td>
                                 <%#Eval("ChannelName").ToString()%>
                                </td>
                                <td>
                                    <%#Eval("FolderName").ToString()%>
                                  <%--<asp:Label ID ="FileFolderName" runat="server"></asp:Label>--%>
                                </td>
                            </tr>
                        </ItemTemplate>
                    </asp:Repeater>
                </tbody>
           </table>

 

  四、运行效果如图:

运行效果图.png

上一篇:ASP.NET Core跨平台开发:Kestrel服务器

下一篇:如何用.net core创建Self-Contained控制台

扫码关注微信公众号了解更多详情

跟技术大咖,专业导师一起交流学习

姓名
电话
Q Q

在线留言

请您把问题留下,我们为您提供专业化的解答!

QQ咨询
  1. 招生问答
  2. 热门点击
  3. 最新更新
  4. 推荐文章

关于我们

学校成就

就业保障

联系方式

联系电话:400-160-2868

在线报名

预约报名

备案号:湘ICP备2020021619号-1
地址:湖南省长沙市高新区麓谷麓松路679号 版权所有:长沙市岳麓职业培训学校

在线咨询
课程咨询 学费咨询 学费分期 入学测试 免费预约 来校路线
初中生 高中生 待业者
400-160-2868

在线客服