我创建了一个代码,用户可以从中下载该文件。将下载的文件仅用于图像文件。
我的代码如下所示。
try
{
System.IO.FileInfo fileInfo = new FileInfo(file.Name);
// replace special characters with blank.
string filename = GeneralMethods.MakeValidFileName(Path.GetFileNameWithoutExtension(file.Name));
filename += fileInfo.Extension;
byte[] obj = (byte[])file.OpenBinary();
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Cache.SetCacheability(System.Web.HttpCacheability.Private);
Response.AppendHeader("Content-Disposition", "attachment; filename= " + filename);
Response.ContentType = MimeMapping.GetMimeMapping(filename);
if (Response.IsClientConnected)
Response.BinaryWrite(obj);
Response.Flush();
// Response.Close();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (Exception ex)
{
}
finally
{
}
当我使用此代码下载.eps
文件时,无法在客户端应用程序中打开该文件。
我的代码中缺少什么?
答案 0 :(得分:0)
尝试修改此行:
Response.AppendHeader("Content-Disposition", "attachment; filename= " + filename);
看起来像这样:
var cd = new System.Net.Mime.ContentDisposition
{
FileName = filename,
Inline = false,
};
Response.AddHeader("Content-Disposition", cd.ToString());
过去,像这样添加Content-Disposition对我有用。
答案 1 :(得分:0)
尝试各种代码后,终于找到了答案。
我的代码中唯一缺少的是在Response对象中定义“Content-Length”标头。
所以代码如下:
try
{
System.IO.FileInfo fileInfo = new FileInfo(file.Name);
string filename = GeneralMethods.MakeValidFileName(Path.GetFileNameWithoutExtension(file.Name));
filename += fileInfo.Extension;
byte[] obj = (byte[])file.OpenBinary();
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Cache.SetCacheability(System.Web.HttpCacheability.Server);
var cd = new System.Net.Mime.ContentDisposition { FileName = file.Name, Inline=false};
Response.AppendHeader("Content-Disposition", cd.ToString());
Response.AppendHeader("Content-Length",obj.Length.ToString());
Response.ContentType = MimeMapping.GetMimeMapping(filename);
if (Response.IsClientConnected)
Response.BinaryWrite(obj);
Response.Flush();
// Response.Close();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (Exception ex)
{
Response.Redirect(Request.UrlReferrer.ToString());
}
finally
{
}
现在它在我的情况下工作...... !!! : - 。)
希望这对其他人也有帮助..
由于