2010-05-06 70 views
0

我正在开发一个项目,该项目需要能够让用户从服务器上的静态位置下载pdf。我正在阅读来自this网站的说明,这是一个旧帖子,我注意到他们在更新中指定了微软的MVC框架早已包含在内,并且Action Result允许他们讨论的相同功能因此使其过时,我看过有点在线,但一直没能找到任何讨论这种内置功能的资源。如果任何人有任何讨论这个问题的链接或其他信息,这将是非常有帮助的。谢谢。在ASP.Net中下载文件MVC网络应用程序

+0

感谢所有为你的建议,我会努力实现基于所提供的信息的演示。 – kingrichard2005 2010-05-06 18:12:13

回答

0

返回FileResult

1
public ActionResult Show(int id) { 
     Attachment attachment = attachmentRepository.Get(id); 

     return new DocumentResult { BinaryData = attachment.BinaryData, 
            FileName = attachment.FileName }; 
    } 

使用这个自定义类,大概类似于FileResult:

public class DocumentResult : ActionResult { 

    public DocumentResult() { } 

    public byte[] BinaryData { get; set; } 
    public string FileName { get; set; } 
    public string FileContentType { get; set; } 

    public override void ExecuteResult(ControllerContext context) { 
     WriteFile(BinaryData, FileName, FileContentType); 
    } 

    /// <summary> 
    /// Setting the content type is necessary even if it is NULL. Otherwise, the browser treats the file 
    /// as an HTML document. 
    /// </summary> 
    /// <param name="content"></param> 
    /// <param name="filename"></param> 
    /// <param name="fileContentType"></param> 
    private static void WriteFile(byte[] content, string filename, string fileContentType) { 
     HttpContext context = HttpContext.Current; 
     context.Response.Clear(); 
     context.Response.Cache.SetCacheability(HttpCacheability.Public); 
     context.Response.ContentType = fileContentType; 
     context.Response.AddHeader("content-disposition", "attachment; filename=\"" + filename + "\""); 

     context.Response.OutputStream.Write(content, 0, content.Length); 

     context.Response.End(); 
    } 
}