ASP.NET文件下載,直接向客戶端輸出文件(轉)


原文地址:http://www.cnblogs.com/mrray/archive/2010/12/22/1914108.html

 默認情況文件下載,直接鏈接指向文件的地址即可,但是有些情況下瀏覽器而是直接打開了文件。例如txt文件的下載,火狐瀏覽器直接打開了txt文件,並不是下載了txt,txt其實被瀏覽器緩存了起來。

pdf同樣如此,一般電腦都安裝了Adobe Reader 這個pdf的閱讀器,當瀏覽器下載pdf的文件時候,默認依然是瀏覽器打開了該pdf文件 而不是下載該pdf文件。

下面的代碼就是 默認不讓瀏覽器打開文件,而且下載文件

Download.ashx

<%@ WebHandler Language="C#" Class="Download" %>

using System;
using System.Web;
using System.IO;

public class Download : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";

        string path = context.Server.UrlDecode(context.Request.QueryString["path"].ToString());

        string fileName = Path.GetFileName(path);//文件名
        
        string filePath = context.Server.MapPath(path);//路徑

        if (File.Exists(filePath))
        {
            //以字符流的形式下載文件
            FileStream fs = new FileStream(filePath, FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            context.Response.ContentType = "application/octet-stream";
            //通知瀏覽器下載文件而不是打開
            context.Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            context.Response.BinaryWrite(bytes);
            context.Response.Flush();
            context.Response.End();
        }
        else
        {
            context.Response.Write("未上傳文件!!");
            context.Response.End();
        }      
        
        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM