使用保存对话框下载文件时出现问题。
我的代码执行时没有错误,但没有显示保存对话框。不是在FF中,不在Chrome中而不是在IE中。附件可以包含以下扩展名:.jpg,.jpeg,.png,.bmp,.pdf,.txt,.docx
。这就是我使用Response.ContentType = "application/octet-stream";
的原因(参见下面的代码)。
protected void btnDownload_OnCommand(object sender, CommandEventArgs e)
{
//Get the attachment to download from the webservice
RCX.AddressAttachment attachment = ShopClient.GetAddressAttachment(ServiceContext,
new AddressAttachmentCriteria()
{
Id = (string) e.CommandArgument //= AttachmentID
});
//Get a random filename
var fileName = string.Format("{0}{1}", Guid.NewGuid(), attachment.FileExtension);
//Get the physicalPath to save the file
var physicalPath = string.Format(@"{0}\Attachments\{1}", System.AppDomain.CurrentDomain.BaseDirectory,
fileName);
//Get the webpath to navigate to the file
var webPath = string.Format("{0}Attachments/{1}", Misc.BaseUrl(Request.Url), fileName);
//Create file if not exists
using (new FileStream(physicalPath, FileMode.OpenOrCreate))
{
}
//Write bytes to file
System.IO.File.WriteAllBytes(physicalPath, attachment.Attachment);
var fileInfo = new FileInfo(physicalPath);
//Try to open the save dialog, what is wrong here?
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0};", fileName));
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.WriteFile(physicalPath);
Response.End();
}
执行WriteAllBytes(string path, byte[] bytearray)
方法后文件存在。
如果我在我的代码中导航到webPath,我也可以在浏览器中看到该文件(参见下面的代码)。
Response.Redirect(webPath);
我可能做错了什么?
非常感谢。
答案 0 :(得分:0)
试试这个
Response.Flush(); 在Response.End();
之前