[英]Unable to download docx file using C#
This is my code and I am trying since hours to download the docx file. 这是我的代码,我正在尝试下载docx文件。 but no success.
但没有成功。 Where I might be lagging, need a slight hint.
我可能会滞后,需要一点点暗示。
if (File.Exists(sTempPath + sCreateFileName))
{
FileInfo file =new FileInfo(sTempPath + sCreateFileName);
Response.ClearContent();
// LINE1: Add the file name and attachment, which will force the open/cancel/save dialog to show, to the header
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
// Add the file size into the response header
Response.AddHeader("Content-Length", file.Length.ToString());
// Set the ContentType
Response.ContentType = ReturnExtension(file.Extension.ToLower());
// Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
Response.TransmitFile(sTempPath + sCreateFileName);
// End the response
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
and Return content type gives, content type for docx file: 和返回内容类型给出,docx文件的内容类型:
"application/ms-word"
where if sTempPath+sCreateFileName is the whole path of the file. 其中,如果sTempPath + sCreateFileName是文件的整个路径。
Update: I tried content type: 更新:我尝试过内容类型:
application/vnd.openxmlformats-officedocument.wordprocessingml.document
This is not working. 这不起作用。
The correct MIME type for DOCX is not application/msword
but application/vnd.openxmlformats-officedocument.wordprocessingml.document
. DOCX的正确MIME类型不是
application/msword
而是application/vnd.openxmlformats-officedocument.wordprocessingml.document
。
The MIME type you specified is for DOC files. 您指定的MIME类型适用于DOC文件。
Also you might want to put a Response.Flush()
and a Response.End()
instead of the CompleteRequest()
. 您也可能想要放置
Response.Flush()
和Response.End()
而不是CompleteRequest()
。
Try this code 试试这个代码
string FileName = Path.Combine(Server.MapPath("~/physical folder"), attFileName);
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
Response.AddHeader("Content-Disposition", string.Format("attachment; filename = \"{0}\"", System.IO.Path.GetFileName(FileName)));
response.TransmitFile(FileName);
response.Flush();
response.End();
I had the same problem. 我有同样的问题。 For me it works:
对我来说它有效:
using (FileStream fileStream = File.OpenRead(filePath))
{
MemoryStream memStream = new MemoryStream();
memStream.SetLength(fileStream.Length);
fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length);
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
Response.AddHeader("Content-Disposition", "attachment; filename=myfile.docx");
Response.BinaryWrite(memStream.ToArray());
Response.Flush();
Response.Close();
Response.End();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.