[英]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.