遭遇Asp.Net长文件名下载的问题和解决办法
在Asp.Net中写了一个附件上传和下载的程序,附件上传到数据库中,然后将附件的GUID保存起来,我们可以根据GUID来找到数据库中的附件,一般附件下载的代码是:
private void Download(string ID)
{
file = logic.GetAttachmentByID(new Guid(ID));
Response.AddHeader("Content-Type", file.Type);
Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + HttpUtility.UrlEncode(file.FileName) + "\"");
Response.BinaryWrite(file.Data.ToArray());
Response.End();
}
这里比较重要的就是Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + HttpUtility.UrlEncode(file.FileName) + "\"");这里需要对中文文件名进行编码,默认是使用的UTF8编码。但是编码后文件名就会变得很长,比如我现在有一个文件叫:
招标送检样机项目检查登记表(终端)-空.XLS
我们进行网络抓包,可以看到在下载文件的时候的HTTP响应是:
HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 44032
Content-Type: application/vnd.ms-excel
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
MicrosoftSharePointTeamServices: 12.0.0.6219
X-AspNet-Version: 2.0.50727
Content-Disposition: attachment; filename="%e6%8b%9b%e6%a0%87%e9%80%81%e6%a3%80%e6%a0%b7%e6%9c%ba%e9%a1%b9%e7%9b%ae%e6%a3%80%e6%9f%a5%e7%99%bb%e8%ae%b0%e8%a1%a8(%e7%bb%88%e7%ab%af)-%e7%a9%ba.XLS"
Date: Wed, 25 Mar 2009 08:00:26 GMT
可以得到编码后文件名变成了:
%e6%8b%9b%e6%a0%87%e9%80%81%e6%a3%80%e6%a0%b7%e6%9c%ba%e9%a1%b9%e7%9b%ae%e6%a3%80%e6%9f%a5%e7%99%bb%e8%ae%b0%e8%a1%a8(%e7%bb%88%e7%ab%af)-%e7%a9%ba.XLS
这都是在HTTP头里面的,由于浏览器或者其他原因,对于这么长的HTTP头,系统会对字符串进行截止,那么就会造成下载的时候文件名不全或者干脆就是乱码的情况。我试了一下,这个文件的下载在IE8里面
相关文档:
<%@ Page Language="C#" %>
<%@ import Namespace="System.Collections" %>
<script runat="server">
void Page_Load(Object sender, EventArgs e) {
if(!Page.IsPostBack){
ArrayList data = new ArrayList();
data.Add(new Person("Tom",33,true));
data.Add(new Person("Jhon",39,false));
da ......
关闭窗体
1.
this.btnClose.Attributes.Add("onclick", "window.close();return false;");
2.关闭本窗体间跳转到另一个页面
this.HyperLink1.NavigateUrl = "javascript:onclick=window.opener.location.assign
......
错误信息:
回发或回调参数无效。在配置中使用 <pages enableEventValidation="true"/> 或在页面中使用 <%@ Page EnableEventValidation="true" %> 启用了事件验证。出于安全目的,此功能验证回发或回调事件的参数是否来源于最初呈现这些事件的服务器控件。如果数据有效并且是预期的,则使用 ClientScriptMan ......
FileUp.aspx 页面
1<%@ Page language="c#" Codebehind="FileUp.aspx.cs" AutoEventWireup="false" Inherits="TestCenter.FileUp" %>
2<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
3<HTML>
4 <HEAD>
5 &l ......