using System;
using System.IO;
using System.Threading;
using System.Web; namespace 落地页测试代码
{
public class FileDownHelper
{
public FileDownHelper()
{ }
public static string FileNameExtension(string FileName)
{
return Path.GetExtension(MapPathFile(FileName));
}
public static string MapPathFile(string FileName)
{
return HttpContext.Current.Server.MapPath(FileName);
}
public static bool FileExists(string FileName)
{
string destFileName = FileName;
if (File.Exists(destFileName))
{
return true;
}
else
{
return false;
}
}
public static void DownLoadold(string FileName, string name)
{
string destFileName = FileName;
if (File.Exists(destFileName))
{
FileInfo fi = new FileInfo(destFileName);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Buffer = false;
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AppendHeader("Content-Length", fi.Length.ToString());
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.WriteFile(destFileName);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
}
public static void DownLoad(string FileName)
{
string filePath = MapPathFile(FileName);
long chunkSize = ; //指定块大小
byte[] buffer = new byte[chunkSize]; //建立一个200K的缓冲区
long dataToRead = ; //已读的字节数
FileStream stream = null;
try
{
//打开文件
stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
dataToRead = stream.Length; //添加Http头
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachement;filename=" + HttpUtility.UrlEncode(Path.GetFileName(filePath)));
HttpContext.Current.Response.AddHeader("Content-Length", dataToRead.ToString()); while (dataToRead > )
{
if (HttpContext.Current.Response.IsClientConnected)
{
int length = stream.Read(buffer, , Convert.ToInt32(chunkSize));
HttpContext.Current.Response.OutputStream.Write(buffer, , length);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Clear();
dataToRead -= length;
}
else
{
dataToRead = -; //防止client失去连接
}
}
}
catch (Exception ex)
{
HttpContext.Current.Response.Write("Error:" + ex.Message);
}
finally
{
if (stream != null) stream.Close();
HttpContext.Current.Response.Close();
}
}
public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
{
try
{
FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(myFile);
try
{
_Response.AddHeader("Accept-Ranges", "bytes");
_Response.Buffer = false; long fileLength = myFile.Length;
long startBytes = ;
int pack = ; //10K bytes
int sleep = (int)Math.Floor((double)( * pack / _speed)) + ; if (_Request.Headers["Range"] != null)
{
_Response.StatusCode = ;
string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
startBytes = Convert.ToInt64(range[]);
}
_Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
if (startBytes != )
{
_Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - , fileLength));
} _Response.AddHeader("Connection", "Keep-Alive");
_Response.ContentType = "application/octet-stream";
_Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8)); br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + ; for (int i = ; i < maxCount; i++)
{
if (_Response.IsClientConnected)
{
_Response.BinaryWrite(br.ReadBytes(pack));
Thread.Sleep(sleep);
}
else
{
i = maxCount;
}
}
}
catch
{
return false;
}
finally
{
br.Close();
myFile.Close();
}
}
catch
{
return false;
}
return true;
}
}
}

C# 文件下载工具类FileDownHelper的更多相关文章

  1. Java 文件下载工具类

    Java 文件下载工具类 import org.slf4j.Logger; import org.slf4j.LoggerFactory; private static Logger logger = ...

  2. 文件下载工具类 DownLoadUtil 实战

    package com.cloud.mina.util; import java.io.File; import java.io.FileInputStream; import java.io.IOE ...

  3. JavaWeb响应下载(包含工具类)

    纸上得来终觉浅,绝知此事要躬行!今天博主分享是关于javaweb的响应(response)下载 以下是我的Demo: 页面我就粘主要部分的代码 <a href = "${pageCon ...

  4. 分享一个FileUtil工具类,基本满足web开发中的文件上传,单个文件下载,多个文件下载的需求

    获取该FileUtil工具类具体演示,公众号内回复fileutil20200501即可. package com.example.demo.util; import javax.servlet.htt ...

  5. Android两个页面之间的切换效果工具类

    import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; ...

  6. android下载简单工具类

    功能是实现下载文件,图片或MP3等,为了简单起见使用单线程,此代码为MarsAndroid教程的复制品,放在此处,留着参考. 首先是一个得到字节流随后保存到内存卡上的工具类: package com. ...

  7. [C#] 常用工具类——文件操作类

    /// <para> FilesUpload:工具方法:ASP.NET上传文件的方法</para> /// <para> FileExists:返回文件是否存在&l ...

  8. Android基于Retrofit2.0 +RxJava 封装的超好用的RetrofitClient工具类(六)

    csdn :码小白 原文地址: http://blog.csdn.net/sk719887916/article/details/51958010 RetrofitClient 基于Retrofit2 ...

  9. java下载Excel模板(工具类)

    一次文件下载记录 一次不成熟的文件下载操作记录,希望能对需要的人有所帮助. 1.前端代码 $("#downloadModel").click(function(){ var mod ...

随机推荐

  1. tsc.exe 已退出 代码为 1

    从微软官网下载TypeScript_Dev14Full,解决问题,下载地址https://www.microsoft.com/zh-CN/download/confirmation.aspx?id=4 ...

  2. DAY23、面向对象特性

    一.复习1.类: 对象属性的查找顺序:先找自身再找类 类的名称空间:直接写在类中 对象的名称空间:写在__init__方法中,通过self.属性形成名称空间中的名字 类的方法:在类中用@classme ...

  3. Transformer

    参考资料: [ERT大火却不懂Transformer?读这一篇就够了] https://zhuanlan.zhihu.com/p/54356280 (中文版) http://jalammar.gith ...

  4. Nginx LOG阶段里log模块

    L68 log_format 指令 syntax : name [escape =default|josn|none] string "...."; default : combi ...

  5. BIZ中model.getSql源码分析

    功能:根据model.xml文件中配置的sql,获取对应的动态sql结果. 实例代码:String sql1 = model.getSql(dao.dbMeta());String sql2 = mo ...

  6. settings 配置 + 测试环境搭建

    若想将模型转为mysql数据库中的表,需要在settings中配置: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', ...

  7. pjb fabu

    #!/bin/bash PyPath=/opt/shell/mysql LocaName=`pwd` bagname=`basename $LocaName` sleep 1s ConfList=`p ...

  8. JavaEEMybatis基础整理

    一:对原生态JDBC问题的总结 新项目要使用mybatis作为持久层框架,由于本人之前一直使用的Hibernate,对mybatis的用法实在欠缺,最近几天计划把mybatis学习一哈,特将学习笔记记 ...

  9. 《Exception团队》第一次作业:团队亮相

    一.项目基本介绍 项目 内容 这个作业属于哪个课程 任课教师博客主页链接 这个作业的要求在哪里 作业链接地址 团队名称 Exception 作业学习目标 深入了解软件思想,强化编程技术 二.正文 1. ...

  10. hadoop记录-hive常见设置

    分区表 set hive.exec.dynamic.partition=true; set hive.exec.dynamic.partition.mode=nonstrict;create tabl ...