从服务器上边下载文件到客户机的实现.

来源:互联网 发布:nginx 默认跳转页面 编辑:程序博客网 时间:2024/04/26 05:10
FileInfo fi=new FileInfo(ls_path3);
Response.Clear();
Response.ClearHeaders();
Response.Buffer=false;
                                               
Response.AppendHeader("Content-Disposition","attachment;filename=" + System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(ls_path3)));
Response.AppendHeader("Content-Length",fi.Length.ToString());
Response.ContentType="application/octet-stream";
Response.WriteFile(ls_path3);
Response.Flush();
Response.End();



关于asp.net中文文件名超长的下载问题

经测试,在header中的filename 中文只能18个,英文165个
按中文一个在UTF8里是9个字节( System.Text.UnicodeEncoding.UTF8.GetByteCount()方法获取每个中文为3个字符),应该是18*9=162<165)
因此在长中文文件名下载时做以下处理:
当文件名GetByteCount大于57时(没有判断中英文混合的情况)则截取文件名
        Dim FullFileName As String = Server.MapPath("qbuttom3.aspx/../../") & "temp/" & FileName
        If System.IO.File.Exists(FullFileName) = True Then
            Dim strLenth As Integer = System.Text.UnicodeEncoding.UTF8.GetByteCount(ModName)
                If strLenth > 57 Then
                    ModName = ModName.Substring(0, 17) + "_.xls"
                End If
            Response.Clear()
            Response.ContentType = "application/vnd.ms_excel"
            Response.AppendHeader("Content-Disposition", "attachment; filename=" & Server.UrlEncode(ModName))
            Response.Flush()
            Response.WriteFile(FullFileName)
        End If
注:
许多情况下当程序采用了Server.HTMLEncode 和 Server.URLEncode 先对中文进行过编码以后,系统依然显示乱码,根据微软的解释,这种情况跟IIS有关,微软提供的原因是未打Pack3的IIS 假定每个字符两个字节,而某些 UTF8 字符使用三个字节。这样,所创建的缓冲区太小,无法容纳这些字节,导致产生乱码,解决方法就是给IIS打Pack3
下载地址如下
 :
立即下载 Q249831_w2k_sp3_x86_EN.exe

中文(简体):
立即下载 Q249831_w2k_sp3_x86_CN.exe

原创粉丝点击