asp.net实现文件下载(wap手机下载)

来源:互联网 发布:天府广场附近美食 知乎 编辑:程序博客网 时间:2024/04/27 13:28

这个问题困扰了我两天,手机下载

 protected void Page_Load(object sender, EventArgs e)
    {
        string filename = Server.UrlDecode(Request["upload"]);
        string filePath = Server.MapPath("upload/" + filename);//路径
        FileDownload(filePath);
    }

/// <summary>
    /// 文件下载
    /// </summary>
    /// <param name="FullFileName"> </param>
    private void FileDownload(string FullFileName)
    {
        try
        {
            FileInfo DownloadFile = new FileInfo(FullFileName);
            if (DownloadFile.Exists)
            {
                Response.Clear();
                Response.ClearHeaders();
                Response.Buffer = false;
                //Response.ContentType = "application/octet-stream";//通知浏览器下载文件而不是打开
                Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(DownloadFile.FullName, System.Text.Encoding.UTF8));
                Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
                switch (DownloadFile.Extension.ToLower())//这是必须,电脑上浏览就不需要
                {
                    case ".pdf":
                        Response.ContentType = "application/pdf";
                        break;
                    case ".txt":
                        Response.ClearHeaders();
                        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(DownloadFile.FullName, System.Text.Encoding.ASCII));
                        Response.ContentType = "text/plain";
                        break;
                    case ".jpg":
                        Response.ContentType = "image/jpeg";
                        break;
                    case ".doc":
                        Response.ContentType = "application/msword";
                        break;
                    case ".zip":
                        Response.ContentType = "application/zip";
                        break;
                    case ".rar":
                        Response.ContentType = "application/rar";
                        break;
                    case ".xls":
                        //Response.ContentType = "application/xls";
                        Response.ContentType = "application/vnd.ms-excel";
                        break;
                    default:
                        Response.ContentType = "application/unknown";
                        break;
                }
                Response.WriteFile(DownloadFile.FullName);
                Response.Flush();
                Response.End();
            }
            else
            {
                Label1.Text="文件名不存在";
            }
        }
        catch(Exception ex)
        {
            Label1.Text = "aa";
            Label1.Text = ex.Message;
        }
    }

原创粉丝点击