2016-09-22 6 views
0

私のPCにはというpdfファイルを持っているフォルダがあります。今はその名前に従って表示したいと思います。私はいくつかのコーディングをしてそれはpdfも表示されます。しかし、その後、再びエラーメッセージは、「開いているファイルができません。ファイル形式とerrowがあります」と言って表示されますローカルドライブにPDFを表示しますか?

をこれは、あなたがハンドラを作成する場合は、「DownloadDocを言う私のコード

try 
{ 
     this.Response.ContentType = "application/pdf"; 
     this.Response.TransmitFile(FilePath+name); 
     this.Response.End(); 
} 
catch (Exception ex) 
{ 
    WebMsgBox.Show(ex.Message); 
} 
+0

あなたはpdfが壊れている可能性があります。どのファイルが壊れているかを調べるために手動で1つずつ開きます。 –

+0

'this.Response.End();'をしないでください。 –

+0

あなたはそのコードをどこに置いていますか?たぶんあなたがウェブフォームの中に持っていれば、他のデータも送るでしょう。これはハンドラの内部にある必要があります – Aristos

答えて

0

です「.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#が必要でした。私はあなたが上記を翻訳することができると確信しています。

関連する問題