[英]Handling file download in ASP.NET
在C#或VB.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
我收到這樣的錯誤消息:
你調用的對象是空的。
r.ContentType =“ application / 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
我班上怎么了?
謝謝。
更換
Dim r As HttpResponse
同
Dim r as HttpResponse = HttpContext.Current.Response
在AIUFileHandler
類中
在使用它之前,需要在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
順便說一句,我使用下一個代碼將文件作為附件發送給用戶:
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.