繁体   English   中英

在本地驱动器中查看pdf?

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM