2010-10-25 117 views
1

在C#或VB.NET中的建議是可以接受的。在ASP.NET中處理文件下載

我有一個類來處理像下面的文件下載鏈接ASP.NET項目:

Public Class AIUFileHandler  
    Public Shared Sub DownloadFileHandler(ByVal fileName As String, ByVal filePath As String)  
     Dim r As HttpResponse  
     r.ContentType = "application/vnd.openxmlformats-officedocument.presentationml.presentation" 
     r.AddHeader("content-disposition", String.Format("attachment;filename={0}", fileName)) 
     r.TransmitFile(filePath)  
     r.[End]()  
    End Sub  
End Class 

然後,我調用該函數從這樣的代碼在ASP.NET頁面的背後:

Protected Sub btnGetForm_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnGetForm.Click 
    Dim fileName = "test.docx" 
    Dim filePath = Server.MapPath("~/pub/test.docx") 
    AIUFileHandler.DownloadFileHandler(fileName, filePath) 
End Sub 

我喜歡這個此錯誤消息:

對象引用不t設置爲對象的實例。

r.ContentType = 「應用/ vnd.openxmlformats-officedocument.presentationml.presentation」

但如果我這樣使用它未做另一個類,它的工作原理:

Protected Sub btnGetForm_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnGetForm.Click 
    Dim fileName = "test.docx" 
    Dim filePath = Server.MapPath("~/pub/test.docx") 
    Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" 
    Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", fileName)) 
    Response.TransmitFile(filePath) 
    Response.[End]() 
End Sub 

什麼我班的問題?

謝謝。

回答

2

替換

Dim r As HttpResponse 

Dim r as HttpResponse = HttpContext.Current.Response 

AIUFileHandler

1

你需要使用它之前初始化DownloadFileHandler方法裏面的r變量:

Dim r As HttpResponse = HttpContext.Current.Response 

或把它作爲參數:

Public Class AIUFileHandler 
    Public Shared Sub DownloadFileHandler(ByVal fileName As String, ByVal filePath As String, ByVal r as HttpResponse) 
     r.ContentType = "application/vnd.openxmlformats-officedocument.presentationml.presentation" 
     r.AddHeader("content-disposition", String.Format("attachment;filename={0}", fileName)) 
     r.TransmitFile(filePath) 
     r.[End]() 
    End Sub 
End Class 

,並呼籲:

Protected Sub btnGetForm_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnGetForm.Click 
    Dim fileName = "test.docx" 
    Dim filePath = Server.MapPath("~/pub/test.docx") 
    AIUFileHandler.DownloadFileHandler(fileName, filePath, Response) 
End Sub 
0

順便說一句,我用下面的代碼將文件發送到用戶作爲附件:

var info = new FileInfo(Server.MapPath(path)); 
Response.Clear(); 
Response.AppendHeader("Content-Disposition", String.Concat("attachment; filename=", info.Name)); 
Response.AppendHeader("Content-Length", info.Length.ToString(CultureInfo.InvariantCulture)); 
Response.ContentType = type; 
Response.WriteFile(info.FullName, true); 
Response.End(); 

你也可以把它包裝成try-finally如果以編程方式生成目標文件,則會阻止:

var info = .. 
try 
{ 
    // do stuff 
} 
finally 
{ 
    File.Delete(info.FullName); 
}