2010-05-06 71 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(); 
    } 
}