使用C#下载文件的多种方法小结

发布时间 2023-09-02 15:52:56作者: yinghualeihenmei

https://pythonjishu.com/bbzsoetttsxyoao/

https://www.cnblogs.com/ning-xiaowo/p/16792303.html

https://blog.csdn.net/yang472024191/article/details/37905749/

using System.Net;

string url = "http://example.com/file.txt";
string filePath = @"C:\Downloads\file.txt";

using (WebClient client = new WebClient())
{
    client.DownloadFile(url, filePath);
}

代码解释:

  • 首先我们引入System.Net命名空间;
  • 然后我们定义要下载的文件的URL和要保存的本地文件路径;
  • 接着使用using语句创建一个WebClient对象,并使用DownloadFile方法将文件下载到本地;

2. HttpWebRequest下载文件

使用HttpWebRequest下载文件是更灵活的下载方法之一,它提供了更多的下载控制选项,例如可以设置请求头、请求超时等。

示例代码:

using System.Net;
using System.IO;
string url = "http://example.com/file.txt"; string filePath = @"C:\Downloads\file.txt"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) using (Stream streamResponse = response.GetResponseStream()) using (Stream streamFile = File.Create(filePath)) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = streamResponse.Read(buffer, 0, buffer.Length)) > 0) { streamFile.Write(buffer, 0, bytesRead); } }

代码解释:

  • 首先我们引入System.NetSystem.IO命名空间;
  • 然后我们定义要下载的文件的URL和要保存的本地文件路径;
  • 接着使用WebRequest的静态方法Create创建一个HttpWebRequest对象;
  • 我们使用GetResponse方法发送请求,并使用HttpWebResponse对象获取响应;
  • 然后我们创建输入和输出流,并使用while循环逐个字节地读取和写入文件内容;

第一种:最简单的超链接方法,<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();

Response.ContentType 的所有类型:
            $mimetypes = array(
                 'ez'         => 'application/andrew-inset',
                 'hqx'         => 'application/mac-binhex40',
                 'cpt'         => 'application/mac-compactpro',
                 'doc'         => 'application/msword',
                 'bin'         => 'application/octet-stream',
                 'dms'         => 'application/octet-stream',
                 'lha'         => 'application/octet-stream',
                 'lzh'         => 'application/octet-stream',
                 'exe'         => 'application/octet-stream',
                 'class'         => 'application/octet-stream',
                 'so'         => 'application/octet-stream',
                 'dll'         => 'application/octet-stream',
                 'oda'         => 'application/oda',
                 'pdf'         => 'application/pdf',
                 'ai'         => 'application/postscript',
                 'eps'         => 'application/postscript',
                 'ps'         => 'application/postscript',
                 'smi'         => 'application/smil',
                 'smil'         => 'application/smil',
                 'mif'         => 'application/vnd.mif',
                 'xls'         => 'application/vnd.ms-excel',
                 'ppt'         => 'application/vnd.ms-powerpoint',
                 'wbxml'         => 'application/vnd.wap.wbxml',
                 'wmlc'         => 'application/vnd.wap.wmlc',
                 'wmlsc'         => 'application/vnd.wap.wmlscriptc',
                 'bcpio'         => 'application/x-bcpio',
                 'vcd'         => 'application/x-cdlink',
                 'pgn'         => 'application/x-chess-pgn',
                 'cpio'         => 'application/x-cpio',
                 'csh'         => 'application/x-csh',
                 'dcr'         => 'application/x-director',
                 'dir'         => 'application/x-director',
                 'dxr'         => 'application/x-director',
                 'dvi'         => 'application/x-dvi',
                 'spl'         => 'application/x-futuresplash',
                 'gtar'         => 'application/x-gtar',
                 'hdf'         => 'application/x-hdf',
                 'js'         => 'application/x-javascript',
                 'skp'         => 'application/x-koan',
                 'skd'         => 'application/x-koan',
                 'skt'         => 'application/x-koan',
                 'skm'         => 'application/x-koan',
                 'latex'         => 'application/x-latex',
                 'nc'         => 'application/x-netcdf',
                 'cdf'         => 'application/x-netcdf',
                 'sh'         => 'application/x-sh',
                 'shar'         => 'application/x-shar',
                 'swf'         => 'application/x-shockwave-flash',
                 'sit'         => 'application/x-stuffit',
                 'sv4cpio'     => 'application/x-sv4cpio',
                 'sv4crc'     => 'application/x-sv4crc',
                 'tar'         => 'application/x-tar',
                 'tcl'         => 'application/x-tcl',
                 'tex'         => 'application/x-tex',
                 'texinfo'     => 'application/x-texinfo',
                 'texi'         => 'application/x-texinfo',
                 't'             => 'application/x-troff',
                 'tr'         => 'application/x-troff',
                 'roff'         => 'application/x-troff',
                 'man'         => 'application/x-troff-man',
                 'me'         => 'application/x-troff-me',
                 'ms'         => 'application/x-troff-ms',
                 'ustar'         => 'application/x-ustar',
                 'src'         => 'application/x-wais-source',
                 'xhtml'         => 'application/xhtml+xml',
                 'xht'         => 'application/xhtml+xml',
                 'zip'         => 'application/zip',
                 'au'         => 'audio/basic',
                 'snd'         => 'audio/basic',
                 'mid'         => 'audio/midi',
                 'midi'         => 'audio/midi',
                 'kar'         => 'audio/midi',
                 'mpga'         => 'audio/mpeg',
                 'mp2'         => 'audio/mpeg',
                 'mp3'         => 'audio/mpeg',
                 'aif'         => 'audio/x-aiff',
                 'aiff'         => 'audio/x-aiff',
                 'aifc'         => 'audio/x-aiff',
                 'm3u'         => 'audio/x-mpegurl',
                 'ram'         => 'audio/x-pn-realaudio',
                 'rm'         => 'audio/x-pn-realaudio',
                 'rpm'         => 'audio/x-pn-realaudio-plugin',
                 'ra'         => 'audio/x-realaudio',
                 'wav'         => 'audio/x-wav',
                 'pdb'         => 'chemical/x-pdb',
                 'xyz'         => 'chemical/x-xyz',
                 'bmp'         => 'image/bmp',
                 'gif'         => 'image/gif',
                 'ief'         => 'image/ief',
                 'jpeg'         => 'image/jpeg',
                 'jpg'         => 'image/jpeg',
                 'jpe'         => 'image/jpeg',
                 'png'         => 'image/png',
                 'tiff'         => 'image/tiff',
                 'tif'         => 'image/tiff',
                 'djvu'         => 'image/vnd.djvu',
                 'djv'         => 'image/vnd.djvu',
                 'wbmp'         => 'image/vnd.wap.wbmp',
                 'ras'         => 'image/x-cmu-raster',
                 'pnm'         => 'image/x-portable-anymap',
                 'pbm'         => 'image/x-portable-bitmap',
                 'pgm'         => 'image/x-portable-graymap',
                 'ppm'         => 'image/x-portable-pixmap',
                 'rgb'         => 'image/x-rgb',
                 'xbm'         => 'image/x-xbitmap',
                 'xpm'         => 'image/x-xpixmap',
                 'xwd'         => 'image/x-xwindowdump',
                 'igs'         => 'model/iges',
                 'iges'         => 'model/iges',
                 'msh'         => 'model/mesh',
                 'mesh'         => 'model/mesh',
                 'silo'         => 'model/mesh',
                 'wrl'         => 'model/vrml',
                 'vrml'         => 'model/vrml',
                 'css'         => 'text/css',
                 'html'         => 'text/html',
                 'htm'         => 'text/html',
                 'asc'         => 'text/plain',
                 'txt'         => 'text/plain',
                 'rtx'         => 'text/richtext',
                 'rtf'         => 'text/rtf',
                 'sgml'         => 'text/sgml',
                 'sgm'         => 'text/sgml',
                 'tsv'         => 'text/tab-separated-values',
                 'wml'         => 'text/vnd.wap.wml',
                 'wmls'         => 'text/vnd.wap.wmlscript',
                 'etx'         => 'text/x-setext',
                 'xsl'         => 'text/xml',
                 'xml'         => 'text/xml',
                 'mpeg'         => 'video/mpeg',
                 'mpg'         => 'video/mpeg',
                 'mpe'         => 'video/mpeg',
                 'qt'         => 'video/quicktime',
                 'mov'         => 'video/quicktime',
                 'mxu'         => 'video/vnd.mpegurl',
                 'avi'         => 'video/x-msvideo',
                 'movie'         => 'video/x-sgi-movie',
                 'ice'         => 'x-conference/x-cooltalk',
            );