Send file to client and delete it
I have a word document in my server, that I want to send to my client. Actually I want them to download that file. I am creating that file in runtime, and I want to delete it after they download it from my server. I'm trying this scenario locally. After the creation of file, my server sends it to client. In web browser I see this:
I don't want this. I want web browser to open save file dialog. I want client to download real file. Here is my code :
Guid temp = Guid.NewGuid();
string resultFilePath = Server.MapPath("~/formats/sonuc_" + temp.ToString() + ".doc");
if (CreateWordDocument(formatPath, resultFilePath , theLst)) {
Response.TransmitFile(resultFilePath);
Response.Flush();
System.IO.File.Delete(resultFilePath);
Response.End();
}
这段代码应该做到这一点,但请注意,这会导致将整个文件加载到服务器的内存中。
private static void DownloadFile(string path)
{
FileInfo file = new FileInfo(path);
byte[] fileConent = File.ReadAllBytes(path);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", file.Name));
HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.BinaryWrite(fileConent);
file.Delete();
HttpContext.Current.Response.End();
}
What you want is not an .aspx
file (which is a web-page) but an .ashx
which can provide the data you need, and set the content-disposition. See this question for an example (here using PDF-downloads):
Downloading files using ASP.NET .ashx modules
You might also try to set the correct content type / mime type for Word, perhaps like the following, or you might take a look at this question.
response.ContentType = "application/msword";
response.AddHeader("Content-Disposition", "attachment;filename="yourFile.doc"");
链接地址: http://www.djcxy.com/p/45454.html
下一篇: 将文件发送到客户端并删除它