asp.net 3.5 (C#) + Vs2008 请教附件下载代码

microlin microlin 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
//我现在代码如下写法,但遇到附件是图片,则打开为空,下载下来也是空,但文件大小还是有的.
//如果是文本文件,直接打开中文会成乱码
//希望懂得人看一下代码,哪里有错指正一下,或有现成可用代码提供也行,谢谢

public partial class FileDown : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string oldName = Server.UrlDecode(Request.QueryString["OldName"]);
string newName = Server.UrlDecode(Request.QueryString["NewName"]);
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Clear();

string url = Path.Combine(ConfigInfo.AnnexsMapPath, newName);

if (System.IO.File.Exists(url))
{

FileInfo info = new FileInfo(url);
string flName = info.Extension;

FileStream fs = new FileStream(url, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[(int)(fs.Length)];
fs.Read(buffer, 0, buffer.Length);
fs.Close();

string ContentType = "";
switch (flName.ToLower())
{
case ".asf":
ContentType = "video/x-ms-asf";
break;
case ".avi":
ContentType = "video/avi";
break;
case ".doc":
ContentType = "application/msword";
break;
case ".zip":
ContentType = "application/zip";
break;
case ".xls":
ContentType = "application/vnd.ms-excel";
break;
case ".gif":
ContentType = "image/gif";
break;
case ".jpg":
case "jpeg":
ContentType = "image/jpeg";
break;
case ".wav":
ContentType = "audio/wav";
break;
case ".mp3":
ContentType = "audio/mpeg3";
break;
case ".mpg":
case "mpeg":
ContentType = "video/mpeg";
break;
case ".rtf":
ContentType = "application/rtf";
break;
case ".htm":
case "html":
ContentType = "text/html";
break;
case ".txt":
ContentType = "text/plain";
break;
default:
ContentType = "application/octet-stream";
break;
}
Response.AddHeader("Content-Disposition", ("attachment; filename=" + HttpUtility.UrlEncode(oldName, System.Text.Encoding.UTF8)));
Response.AddHeader("Content-Length", buffer.Length.ToString());
// Response.Charset = "UTF-8";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = ContentType;
Response.BinaryWrite(buffer);
Response.Flush();
}

}
}
}
...全文

相关推荐

评论 6
收藏 已收藏
分享
返回顶部
microlin
C# 111,129 成员 642,539 内容