1.0以Stream 下载文件
nl.fileid = Int32.Parse(id); //服务器上对应的id
Stream stream = Lawsuit.DownLoad(nl);//服务器上的Stream 数据 Response.Buffer = false;
Response.AddHeader("Connection", "Keep-Alive");
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + url); // 此处文件名如果是中文在浏览器默认是筹码,应该加HttpUtility.UrlEncode(filename) url:为下载文件的服务器地址和名称 while (true) //如果文件大于缓冲区,通过while循环多次加载文件
{
//开辟缓冲区空间
byte[] buffer = new byte[]; //读取文件的数据
int leng = stream.Read(buffer, , );
if (leng == ) //到文件尾,结束
break;
if (leng == ) //读出的文件数据长度等于缓冲区长度,直接将缓冲区数据写入
Response.BinaryWrite(buffer); //向客户端发送数据流
else
{
//读出文件数据比缓冲区小,重新定义缓冲区大小,只用于读取文件的最后一个数据块
byte[] b = new byte[leng]; for (int i = ; i < leng; i++)
b[i] = buffer[i];
Response.BinaryWrite(b);
}
}
stream.Close();//关闭下载文件
Response.End();//结束文件下载
1.1根据流创建pdf
/// <summary>
/// 根据流创建pdf
/// </summary>
/// <param name="_Stream"></param>
/// <returns></returns>
public string CreateCasePDF(Stream _Stream)
{
string pdfUrl = Server.MapPath("../Content/FilePdf");//pdf保存地址
if (Directory.Exists(pdfUrl) == false)//如果不存在就创建PDFFile文件夹
{
Directory.CreateDirectory(pdfUrl);
}
DocClient proxy = new DocClient();
try
{
string guid = Guid.NewGuid().ToString();
FileInfo file = new FileInfo(pdfUrl + guid + ".pdf");
Stream write = file.OpenWrite();
write.Position = long.Parse("");
byte[] buf = new byte[ * ];
int size = -;
long sum = long.Parse("");
while ((size = _Stream.Read(buf, , buf.Length)) > )
{
write.Write(buf, , size);
sum += size;
}
write.Close();
_Stream.Close();
return guid;
}
catch (Exception)
{
return null;
}
}
1.2根据流生成MD5
/// <summary>
/// 获取文件的MD5值
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public static string GetMD5HashFromStream(Stream stream)
{
try
{
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] data = md5.ComputeHash(stream);
StringBuilder sBuilder = new StringBuilder();
for (int i = ; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
return sBuilder.ToString().ToUpper();
}
catch (Exception ex)
{
throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
}
}
1.3删除指定目录下的文件,并再次创建
string path = Server.MapPath("../Content/FilePdf");// 删除指定文件下的文件夹及其文件
Directory.Delete(path, true);
Directory.CreateDirectory(path);
来源地址:http://www.cnblogs.com/chaoa/archive/2012/03/09/2386106.html