asp.net从ftp下载大文件再输出浏览器的实现(对文件同时进行读写操作)
当前位置:点晴教程→知识管理交流
→『 技术文档交流 』
很多时候安全起见,不会让用户通过浏览器直接从ftp下载文件。这时我们需要web从ftp下载文件再输出到浏览器,对于小文件我们可以一次性读到memorystream,然后输出;但是大文件这样实现就会导致服务器内存爆炸,此时我们可以利用filestream,一边从ftp下载数据到本地,一边从本地输出到用户客户端,这样对于再大的文件都不会影响内存。 以下是通过异步的方式实现对下载文件同时进行读写操作的代码(.net framwork 4.5),MD5验证一致: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication6 { public partial class WebForm1 : System.Web.UI.Page { Aspose.Network.Ftp.FtpClient ftpclient = new Aspose.Network.Ftp.FtpClient("xxxx", "xxx", "xxx"); protected void Page_Load(object sender, EventArgs e) { } string fileName = "C4F4EEP0CX00_ECN-52966A.exe"; string downloadPath = string.Empty; string refilename = string.Empty; public async void DownLoadFileAsync() { string extension = Path.GetExtension(fileName); refilename = Path.GetFileNameWithoutExtension(fileName) + DateTime.Now.ToString("yyyyMMddHHmmssffff") + extension; downloadPath = Server.MapPath(Path.Combine("tempFile", refilename)); try { ftpclient.Connect(); ftpclient.Login(); ftpclient.KeepAlive(); //Task.Run()需要.net4.5及以上版本的支持 await Task.Run(() => { ftpclient.Download("CLIENT_TMP//" + fileName, downloadPath); }); //以下代码支持.net 4.0 ,但是需要额外在项目中加一个类TaskEx //await Task.Factory.StartNew(() => { ftpclient.Download("CLIENT_TMP//" + fileName, downloadPath); }); } catch { throw; } finally { ftpclient.Disconnect(); } } //要使用异步,页面配置头需要加Async="true" //<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication6.WebForm1" Async="true" %> protected void Button1_Click(object sender, EventArgs e) { try { //异步从ftp下载文件到web服务器本地文件夹 DownLoadFileAsync(); Response.Clear();//清空缓冲区 Response.Buffer = false;//不从缓冲区返回数据 Response.ContentType = "application/ctet-stream";//设置输出流 Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";"); Response.AddHeader("Connection", "Keep-Alive");//长连接 Thread.Sleep(2000);//等待异步创建文件成功,避免fileStream初始化失败 //FileAccess.Read表示当前流只能读,不能写,如果后续有写操作会报错 //FileShare.ReadWrite 表示当前流在操作磁盘文件过程中其他流可以读也可以写. using (FileStream fileStream = new FileStream(downloadPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (BinaryReader br = new BinaryReader(fileStream)) { int length = 2048; //获取br.BaseStream.Length时值会随着ftp下载而变化,每次获取都会更新 //br.ReadBytes()读取完后br.BaseStream.Position会前移. while (br.BaseStream.Position < br.BaseStream.Length) { length = br.BaseStream.Length - br.BaseStream.Position > 2048 ? 2048 : (int)(br.BaseStream.Length - br.BaseStream.Position); Response.BinaryWrite(br.ReadBytes(length)); } } } } catch (Exception ex) { Response.Write($"<script>alert(''下载失败:{ex.Message}'')</script>"); } finally { //下载完成后删除本地文件夹的文件 try { File.Delete(downloadPath); } catch { } Response.End(); } } } } 该文章在 2021/3/3 11:12:04 编辑过 |
关键字查询
相关文章
正在查询... |