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. Spring通过注释配置Bean2 关联关系

    接着我们讲讲关联关系的配置,我们耳熟能详的MVC结构,Controller关联着Service,Service关联着UserRepository,接着上一节的代码,完成上诉功能 在Main方法里,我们 ...

  2. Java 多线程加锁的方式总结及对比(转载)

    转自https://blog.csdn.net/u010842515/article/details/67634813 参考博文:http://www.cnblogs.com/handsomeye/p ...

  3. Java中的String,StringBuilder,StringBuffer

    String被final修饰,不可变,每次更改其实是重新创建了一个对象.StringBuilder,StringBuffer是可变的. StringBuffer是线程安全的,StringBuilder ...

  4. springboot aop 拦截接口执行时间

    /** * @description: 记录接口执行时间日志的记录 * @author: * @create 2018-12-27 16:32 */ @Target(ElementType.METHO ...

  5. C语言博客作业04--数组

    1.本章学习总结 1.1 思维导图 1.2 本章学习体会及代码量学习体会 1.2.1 学习体会 关于数组,数组是最基本的构造类型,它是一组相同类型数据的有序组合.数组中的元素在内存中连续存放,每个元素 ...

  6. luogu3687-[ZJOI2017] 仙人掌

    Description P3687 [ZJOI2017]仙人掌 - 洛谷 | 计算机科学教育新生态 Solution 我们先考虑只有一棵树如何处理. 仙人掌可以看做若干环的集合. 特别的, 对于一条没 ...

  7. Bootstrap 模态框(Modal)插件id冲突

    <!DOCTYPE html><html><head>    <meta charset="utf-8">     <titl ...

  8. 【dp】导弹拦截

    题目链接 https://www.luogu.org/problemnew/show/P1020 题目描述 某国为了防御敌国的导弹袭击,发展出一种导弹拦截系统.但是这种导弹拦截系统有一个缺陷:虽然它的 ...

  9. ELK-filebeat收集日志到Kafka,并转存ES

    https://blog.51cto.com/tryingstuff/2052271 场景需求 在有些不需要安装java环境的服务器如Nginx,php等为主的web 应用可以使用filebeat来对 ...

  10. BUG-‘Tokenizer’ object has no attribute ‘oov_token’

    使用keras包实现NLP问题时,报错 /lib/python3./dist-packages/keras/preprocessing/text.py”, line , in texts_to_seq ...