2014-04-01 40 views
1

我在我的服务器中有一个word文档,我想发送给我的客户端。其实我希望他们下载该文件。我在运行时创建该文件,并且我想在从服务器下载它之后将其删除。我在本地尝试这种情况。创建文件后,我的服务器将其发送给客户端。在Web浏览器中我看到这一点:发送文件给客户端并将其删除

enter image description here

我不想这样。我希望Web浏览器打开保存文件对话框。我希望客户端下载真实文件。这里是我的代码:

  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(); 
      } 

回答

6

这段代码应该可以做到,但注意到这会导致将整个文件加载到服务器的内存中。

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(); 
} 
1

你想要的是不是一个.aspx文件(这是一个网页),但一个.ashx它可以提供你所需要的数据,并设置内容处置。见为例此问题(这里使用PDF的下载):

Downloading files using ASP.NET .ashx modules

您也可以尝试设置正确的内容类型/ MIME类型的Word,也许像下面,否则可能会take a look at this question

response.ContentType = "application/msword"; 
response.AddHeader("Content-Disposition", "attachment;filename=\"yourFile.doc\""); 
+0

既然你提到了,我一直在关注这个例子:http://davidarodriguez.com/blog/2013/05/29/downloading-files-from-a-server-to-client-使用-asp-net-when-file-size-is-too-big-for-memorystream-using-generic-handlers-ashx /但是必须将文件名传递给.ashx类? – MilesDyson

+1

您可以将一个名称传递给.ashx,或者让ashx从某处获取该文件。重点是您必须指定要传输到客户端/浏览器的数据类型,以及您希望如何处理这些数据,这是通过指定内容类型和标题来完成的。 – Kjartan

相关问题