2016-09-22 2 views
0

내 컴퓨터에는의 PDF 파일이있는 폴더가 있으며 이제 이름에 따라 표시하려고합니다. 나는 몇몇 부호를하고 그것은 pdf를 또한 표시한다. 그러나 다시 오류 메시지가 후라고 나타납니다 "파일 열기를 할 수 없습니다. 파일 형식의 errow있다"로컬 드라이브에서 PDF보기?

이것은 당신이 핸들러를 작성하는 경우

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

그러면 PDF가 손상되었을 수 있습니다. 하나씩 수동으로 열어 손상된 것을 찾으십시오. –

+0

'this.Response.End();'하지 마십시오. –

+0

그 코드는 어디에 두어야합니까? 어쩌면 다른 형식의 데이터도 웹 양식에 포함되어있을 수 있습니다. 이것은 핸들러 내부에 있어야합니다. – Aristos

답변

0

말을 내 코드 "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#을 원했습니다. 위의 내용을 번역 할 수있을 것입니다.