2013-05-24 2 views
3

이 웹 사이트에는 아파치 지원이 없지만 특정 디렉토리에서만 이미지를 다운로드 할 수 있어야합니다. 어떻게해야합니까? 이 사이트는 ASP.NET 지원 만 가지고 있으며, 그것은 나를 죽이고 있습니다! 이 링크를 발견 : How to download files in mvc3?하지만 그 코드를 어디에 넣을 지, 심지어는 그 코드가 나를 도울 것입니다.ASP.NET 다운로드 가능한 이미지 파일?

도움이 될 것입니다. A 출발점 또는 무엇인가 ...

내가 HTML로 이것을 할 수있는 방법이 있나? 예를 들어 다운로드 링크를 HTML 파일을 가리 키도록 설정하면 HTML 파일이 이미지 파일을 가져 와서 다운로드 할 수있게됩니다.

는 지금까지라는 파일에 다음 ASP 코드가 있습니다 Default.asp를 잘 다운로드를 시작

을하지만, 빈 파일 (download.jpg)을 다운로드합니다. 다운로드 할 실제 이미지 파일에 다음 코드를 어떻게 가리킬 수 있습니까?

<%@ Language=VBScript %> 
<% Option Explicit 

Response.ContentType = "application/octet-stream" 
Response.AddHeader "Content-Disposition", "attachment; filename=" + "download.jpg" 

%> 

동일한 디렉토리 내에도 "download.jpg"라는 파일이 있지만 실제로 이미지를 다운로드하지 않습니다. 대신 90 바이트 빈 이미지 파일을 다운로드합니다.

이 난 행운과 함께이 시도 :

<%@ Language=VBScript %> 
<% Option Explicit 

Response.ContentType = "application/octet-stream" 
Response.AddHeader "Content-Disposition","attachment; filename=07awardee.png" 
Response.TransmitFile Server.MapPath("~/images/07awardee.png") 
Response.End 

%> 

그리고 네, 저는 서버 루트에, 심지어 Default.asp를이 폴더 루트에 07awardee.png/이미지에서 07awardee.png 파일이 있습니다. 알렉! 여기서 무엇을 줄까요? 파일은 392 바이트로 조금 더 커졌지 만 여전히 이미지 파일로 읽을 수는 없습니다 ... 저는 인터넷을 검색해 왔지만이 파일은 작동해야하지만 실제로는 그렇지 않습니다! 여기에 무슨 문제가있을 수 있습니까?

답변

1

OMG, 나는 바위 콘텐츠 형식을 제공해야한다. 이것이 이루어지는 방식입니다. 그것으로 불리는 파일, download.aspx, 입력 다음 코드를 작성 :

<%@ Page language="vb" runat="server" explicit="true" strict="true" %> 
<script language="vb" runat="server"> 
Sub Page_Load(Sender As Object, E As EventArgs) 
    Dim strRequest As String = Request.QueryString("file") 
    If strRequest <> "" AND strRequest.EndsWith(".jpg") OR strRequest.EndsWith(".jpeg") OR strRequest.EndsWith(".png") OR strRequest.EndsWith(".gif") OR strRequest.EndsWith(".pdf") OR strRequest.EndsWith(".doc") OR strRequest.EndsWith(".docx") OR strRequest.EndsWith(".bmp") Then 
     Dim path As String = Server.MapPath(strRequest) 
     Dim file As System.IO.FileInfo = New System.IO.FileInfo(path) 
     If file.Exists Then 
      Response.Clear() 
      Response.AddHeader("Content-Disposition", "attachment; filename=" & file.Name) 
      Response.AddHeader("Content-Length", file.Length.ToString()) 
      Response.ContentType = "application/octet-stream" 
      Response.WriteFile(file.FullName) 
      Response.End 
     Else 
      Response.Write("This file does not exist.") 
     End If 
    Else 
     Response.Write("You do not have permission to download this file type!") 
    End If 
End Sub 
</script> 

를 이제, 당신이 (모든 파일)을 다운로드 할 파일을 얻고 싶은 경우에, 너무처럼 링크 :

<a href="download.aspx?file=/images/logo.gif">Download the logo image</a> 

그리고 그녀가 쓴 것이 전부입니다!

+3

다운로드 금지 파일 (예 : download.aspx? file = ~/web.config 또는 download.aspx? file = ../../../secretfile.txt)을 보호하지 못하도록하십시오. https://www.owasp.org/index.php/Top_10_2013-A4를 참조하십시오. –

+0

특정 파일 형식 만 허용하는 감사의 답변이 업데이트되었습니다. 이것은 지금 완벽하게 잘되어야합니다! –

1

당신은 헤더를 삭제하고 올바른 헤더와

Response.Clear() 
Response.AppendHeader("Content-Disposition", "attachment; filename=somefilename") 
Response.ContentType = "image/jpeg" 
Response.TransmitFile(Server.MapPath("/xyz.jpg")); 
Response.End(); 
+0

것을 C#으로 할 건가요? 그렇다면,이 구문 앞에 '<% @ Language = C# %>'줄을 추가해야 구문이 작동합니다. 나는 이것을 시험 할 것이다 ... 바로 돌아가서 그것이 효과가 있는지 알려줄 것이다. 'Server.MapPath ("/ xyz.jpg")'가 'default.asp' 파일의 위치에 상대적인 파일에 링크되어 있는지 궁금합니다. 또는 사이트의 루트 (http://mydomain.com)와 관련된 파일에 링크되어 있습니까? –

+0

이것은 작동하지 않으며, 매번 손상된 330 바이트 파일을 다운로드합니다. 파일이 존재합니다. 아마도'Web.config'에서 변경해야 할 일이 있을까요? 수업을 추가해야합니까? 또한 구문이 잘못되었습니다. 세미콜론이 누락되었습니다. –

+0

모든 브라우저를 사용해 보셨습니까? 그것은 브라우저와 함께 문제가 될 수 있습니다 .. 당신이 손상된 파일을 다운로드하고 있기 때문에 response.write 파일 경로와 실제 파일 경로와 비교하여 둘 다 똑같은지 확인하는 것이 좋습니다. – Ratna

2

Request.End가있는 .aspx 페이지는 ThreadAbortException을 던지고 서버 성능에 좋지 않습니다. 너무 많은 경우 서버가 손상 될 수 있습니다. 그래서 당신은 그것을 피하기를 원할 것입니다. http://weblogs.asp.net/hajan/archive/2010/09/26/why-not-to-use-httpresponse-close-and-httpresponse-end.aspx

이 문제를 처리하는 방법은 HttpHandler (.ashx)를 사용하여 다운로드 가능한 이미지 파일을 제공하는 것입니다.

//<%@ WebHandler Language="VB" Class="DownloadImage" %> // uncomment this line! 

Public Class DownloadImage : Implements IHttpHandler 
    Protected EnabledTypes() As String = New String() {".jpg", ".gif", ".png"} 

    Public Sub ProcessRequest(ByVal context As HttpContext) _ 
    Implements IHttpHandler.ProcessRequest 
    Dim request = context.Request 
    If Not String.IsNullOrEmpty(request.QueryString("file")) Then 
     Dim path As String = context.Server.MapPath(request.QueryString("file")) 
     Dim file As System.IO.FileInfo = New System.IO.FileInfo(path) 
     If file.Exists And EnabledTypes.Contains(file.Extension.ToLower()) Then 
     context.Response.Clear() 
     context.Response.AddHeader("Content-Disposition", _ 
      "attachment; filename=" & file.Name) 
     context.Response.AddHeader("Content-Length", file.Length.ToString()) 
     context.Response.ContentType = "application/octet-stream" 
     context.Response.WriteFile(file.FullName) 
     Else 
     context.Response.ContentType = "plain/text" 
     context.Response.Write("This file does not exist.") 
     End If 
    Else 
     context.Response.Write("Please provide a file to download.") 
    End If 
    End Sub 

    Public ReadOnly Property IsReusable() As Boolean _ 
     Implements IHttpHandler.IsReusable 
    Get 
     Return True 
    End Get 
    End Property 
End Class 

당신이 이미지 파일에 대한 검사를 구현해야합니다 그렇지 않으면 당신은 잠재적 인 보안 문제를 가지고, 내 구현은 C#으로했고 훨씬 더 코드 (포함 이미지 스케일링 옵션 등)을 가지고 있기 때문에 나는 코드의 일부를 사용했다. (사용자는 웹을 다운로드 할 수 있습니다.데이터베이스 암호가 저장되는 설정)

링크가 될 것입니다 :

<a href="/DownloadImage.ashx?file=/images/logo.gif">Download image</a> 
+0

' 'Contains'는 'System.Array'의 멤버가 아닙니다 –

+0

좋아, VB에서 배열을 제대로 처리하지 못하기 때문에 코드가 조금 바뀌 었습니다. 'Contains'는 C#에서만 작동합니다! 하지만 당신의 httphandler 구현을 사용하기로 결정 했으니까요. httphandler를 사용하고'Response.End'를 제거해 주신 것에 대해 감사드립니다. –

+0

Array.Contains는 .NET에서 Linq를 사용하여 작동합니다. 확장 기능입니다. 'Imports System.Linq'을 추가하십시오. – Willem

관련 문제