using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
namespace WebDownload
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string str = @"image/测试.jpg";
string path = Server.MapPath(str);
if (File.Exists(path))
{
string fileName = System.IO.Path.GetFileName(path); // 获取文件的名字
//if (Request.UserAgent.Contains("MSIE") || Request.UserAgent.Contains("msie"))
//{
// //如果客户端使用 Microsoft Internet Explorer,则需要编码
// fileName = ToHexString(fileName); // 如果使用 fileName = Server.UrlEncode(fileName); 则会出现上文中出现的情况
//}
if (Request.UserAgent.ToLower().IndexOf("msie") > -1)
{
//当客户端使用IE时,对其进行编码;We should encode the filename when our visitors use IE
//使用 ToHexString 代替传统的 UrlEncode();We use "ToHexString" replaced "context.Server.UrlEncode(fileName)"
fileName = ToHexString(fileName);
}
System.IO.FileInfo file = new System.IO.FileInfo(path);
Response.Clear();
// Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);//设置读取的文件头 使用file.Name 会造成中文名乱码
if (Request.UserAgent.ToLower().IndexOf("firefox") > -1)
{
//为了向客户端输出空格,需要在当客户端使用 Firefox 时特殊处理
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
}
else
{
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
}
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";//设置输出类型 这里可以保存在数据库中 动态实现类型
Response.WriteFile(file.FullName);//输出
Response.End();
}
}
/// <summary>
/// 为字符串中的非英文字符编码
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public string ToHexString(string s)
{
char[] chars = s.ToCharArray();
StringBuilder builder = new StringBuilder();
for (int index = 0; index < chars.Length; index++)
{
bool needToEncode = NeedToEncode(chars[index]);
if (needToEncode)
{
string encodedString = ToHexString(chars[index]);
builder.Append(encodedString);
}
else
{
builder.Append(chars[index]);
}
}
return builder.ToString();
}
/// <summary>
///指定 一个字符是否应该被编码
/// </summary>
/// <param name="chr"></param>
/// <returns></returns>
private bool NeedToEncode(char chr)
{
string reservedChars = "$-_.+!*'(),@=&";
if (chr > 127)
return true;
if (char.IsLetterOrDigit(chr) || reservedChars.IndexOf(chr) >= 0)
return false;
return true;
}
/// <summary>
/// 为非英文字符串编码
/// </summary>
/// <param name="chr"></param>
/// <returns></returns>
private string ToHexString(char chr)
{
UTF8Encoding utf8 = new UTF8Encoding();
byte[] encodedBytes = utf8.GetBytes(chr.ToString());
StringBuilder builder = new StringBuilder();
for (int index = 0; index < encodedBytes.Length; index++)
{
builder.AppendFormat("%{0}", Convert.ToString(encodedBytes[index], 16));
}
return builder.ToString();
}
}
}
c# web 下载文件(解决中文文件名乱码问题)
最新推荐文章于 2022-02-09 17:27:56 发布