随笔 - 493  文章 - 0  评论 - 97  阅读 - 239万

C#文件下载的几种方式

From: https://www.cnblogs.com/cang12138/p/5520758.html

 

第一种:最简单的超链接方法,<a>标签的href直接指向目标文件地址,这样容易暴露地址造成盗链,这里就不说了

1、<a>标签

<a href="~/Home/download?id=1">Click to get file</a>

2、后台C#下载

html:

<a href="~/Home/download?id=1">下载</a>

C#:

(1)返回filestream

public FileStreamResult download()
{
     string fileName = "aaa.txt";//客户端保存的文件名
     string filePath = Server.MapPath("~/Document/123.txt");//路径
     return File(new FileStream(filePath, FileMode.Open), "text/plain", fileName);//“text/plain”是文件MIME类型
}

(2)返回file

public FileResult download()
{
    string filePath = Server.MapPath("~/Document/123.txt");//路径
    return File(filePath, "text/plain", "1234.txt"); //1234.txt是客户端保存的名字
}

(3)TransmitFile方法

复制代码
复制代码
public void download()
{
    string fileName = "aaa.txt";//客户端保存的文件名
    string filePath = Server.MapPath("~/Document/123.txt");//路径
    FileInfo fileinfo = new FileInfo(filePath);
    Response.Clear();         //清除缓冲区流中的所有内容输出
    Response.ClearContent();  //清除缓冲区流中的所有内容输出
    Response.ClearHeaders();  //清除缓冲区流中的所有头
    Response.Buffer = true;   //该值指示是否缓冲输出,并在完成处理整个响应之后将其发送
    Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
    Response.AddHeader("Content-Length", fileinfo.Length.ToString());
    Response.AddHeader("Content-Transfer-Encoding", "binary");
    Response.ContentType = "application/unknow";  //获取或设置输出流的 HTTP MIME 类型
    Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); //获取或设置输出流的 HTTP 字符集
    Response.TransmitFile(filePath);
    Response.End();
}
复制代码
复制代码

(4)Response分块下载(服务器下载文件的大小有限制,更改iis等都无法解决,感觉可能跟服务器上的安全狗有关,最后用下面的方法解决下载问题)

复制代码
复制代码
public void download()
{
    string fileName = "456.zip";//客户端保存的文件名
    string filePath = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "Excel/123.zip";

    System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);

    if (fileInfo.Exists == true)
    {
        //每次读取文件,只读取1M,这样可以缓解服务器的压力
        const long ChunkSize = 1048576;
        byte[] buffer = new byte[ChunkSize];

        Response.Clear();
        //获取文件
        System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
        //获取下载的文件总大小
        long dataLengthToRead = iStream.Length;
//二进制流数据(如常见的文件下载) Response.ContentType = "application/octet-stream"; //通知浏览器下载文件而不是打开 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName)); using (iStream)//解决文件占用问题,using 外 iStream.Dispose() 无法释放文件 { while (dataLengthToRead > 0 && Response.IsClientConnected) { int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小 Response.OutputStream.Write(buffer, 0, lengthRead); Response.Flush(); dataLengthToRead = dataLengthToRead - lengthRead; } iStream.Dispose(); iStream.Close(); } Response.Close(); Response.End(); } }
复制代码
复制代码

(5)流方式下载

复制代码
复制代码
public void download()
{
    string fileName = "456.zip";//客户端保存的文件名
    string filePath = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "Excel/123.zip";//以字符流的形式下载文件 
    FileStream fs = new FileStream(filePath, FileMode.Open);
    byte[] bytes = new byte[(int)fs.Length];
    fs.Read(bytes, 0, bytes.Length);
    fs.Close();
//二进制流数据(如常见的文件下载) Response.ContentType = "application/octet-stream"; //通知浏览器下载文件而不是打开 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); Response.BinaryWrite(bytes); Response.Flush(); Response.End(); }
复制代码
复制代码

(6)ajax方法

要重点说说这个方法,ajax返回不了文件流,所以说用ajax调用上面任意一种后台方法都要出问题,下载不了文件。

所以,只能让后台返回所需下载文件的url地址,然后调用windows.location.href。

 

优点:ajax可以传好几个参数(当然以json形式),传100个都无所谓。你要是用<a href="网址?参数=值"></a>的方法传100得写死。。。(公司需求,至少要传100多个参数)

缺点:支持下载exe,rar,msi等类型文件。对于txt则会直接打开,慎用!对于其他不常用的类型文件则直接报错。

html:

<input type="button" id="downloadbutton"/>

ajax:

复制代码
复制代码
    $("#downloadbutton").click(function() {
        $.ajax({
            type: "GET",
            url: "/Home/download",
            data: { id: "1" },
            dataType: "json",
            success: function(result) {
                window.location.target = "_blank";
                window.location.href = result;
            }
        })
    });
复制代码
复制代码

后台:

public string download()
{
    string filePath = "Document/123.xls";//路径
    return filePath;
}

 

(7)外网资源下载

复制代码
复制代码
string url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1494331750681&di=7bfc17bf6ef9b5abb02dfd2505a91e90&imgtype=0&src=http%3A%2F%2Fimg.article.pchome.net%2F00%2F35%2F62%2F34%2Fpic_lib%2Fs960x639%2FZhiwu36s960x639.jpg";
string fileName = url.Split('/')[url.Split('/').Length - 1];//客户端保存的文件名  
System.Net.WebClient wc = new System.Net.WebClient();
wc.Encoding = System.Text.Encoding.GetEncoding("gb2312");
byte[] bytes = wc.DownloadData(url);

Response.Clear();
//二进制流数据(如常见的文件下载)
Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开  
Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
复制代码
复制代码

 

posted on   清清飞扬  阅读(7789)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET10 - 预览版1新功能体验(一)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示