[英]View pdf in local drive?
在我的電腦中,有一個包含pdf文件的文件夾,現在我想根據其名稱顯示它。 我已經完成了一些編碼,並且還顯示了pdf 。 但是之后又出現錯誤消息,提示“無法打開文件。文件格式存在錯誤”
這是我的代碼
try
{
this.Response.ContentType = "application/pdf";
this.Response.TransmitFile(FilePath+name);
this.Response.End();
}
catch (Exception ex)
{
WebMsgBox.Show(ex.Message);
}
如果創建處理程序,請說“ DownloadDoc.ashx”,並使用以下代碼:
Option Infer On
Imports System.IO
Imports System.Web
Imports System.Web.Services
''' <summary>
''' Return a pdf document.
''' </summary>
''' <remarks></remarks>
Public Class DownloadDoc
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim srcDir As String = "~/pdfs"
Dim fileType As String = ".pdf"
Dim fname = context.Request.QueryString("name")
Dim actualFile = Path.Combine(context.Server.MapPath(srcDir), fname & suffix) & fileType
If File.Exists(actualFile) Then
context.Response.ContentType = "application/octet-stream"
context.Response.AddHeader("Content-Disposition", "attachment; filename=""" & Path.GetFileName(actualFile) & """")
context.Response.TransmitFile(actualFile)
Else
context.Response.Clear()
context.Response.TrySkipIisCustomErrors = True
context.Response.StatusCode = 404
context.Response.Status = "404 Not Found"
context.Response.Write("<html><head><title>404 - File not found</title><style>body {font-family: sans-serif;}</style></head><body><h1>404 - File not found</h1><p>Sorry, that file is not available for download.</p></body></html>")
context.Response.End()
End If
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
然后,您可以使用普通的<a href="http://www.example.com/DownloadDoc.ashx?name=mypdf">
。
請注意,具有“ .pdf”擴展名是強制性的,因此不能被破壞以從服務器下載任意文件。 您還可以確保僅存在文件名,而沒有任何啟用目錄遍歷的文件,以防萬一在服務器上未安全設置文件許可權。
設置context.Response.ContentType = "application/octet-stream"
是使瀏覽器提供下載文件而不是顯示文件的最接近的方法。
編輯 :哦,對不起,您想要C#。 我相信您將能夠翻譯以上內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.