gpt4 book ai didi

ASP.NET 可下载图像文件?

转载 作者:行者123 更新时间:2023-12-04 02:55:36 27 4
gpt4 key购买 nike

我在这个网站上没有 apache 支持,但我需要能够只允许在特定目录中下载图像。我怎样才能做到这一点?这个网站只支持 ASP.NET,我快死了!注意到此链接:How to download files in mvc3?但不确定将该代码放在哪里,或者即使该代码对我有任何帮助。

任何帮助将不胜感激!起点或其他东西......

有没有一种方法可以在 HTML 中做到这一点?例如,将下载链接设置为指向 html 文件,其中 HTML 文件抓取图像文件并使其本身可下载?

到目前为止,我在名为 default.asp 的文件中有以下 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

%>

是的,我在服务器根目录的 images/07awardee.png 中有 07awardee.png 文件,甚至在 default.asp 所在的文件夹根目录中。哎呀!这里有什么?该文件现在有点大,为 392 字节,但它仍然无法作为图像文件读取...我一直在互联网上搜索,这应该可以工作,但没有!这可能是什么问题?

最佳答案

带有 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) 并使用它来提供可下载的图像文件。我使用了您的一些代码,因为我的实现是在 C# 中并且有更多的代码(包括图像缩放选项等):

//<%@ 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

确保对图像文件进行检查,否则会存在潜在的安全问题。 (用户可以下载存放数据库密码的web.config)

链接会变成:

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

关于ASP.NET 可下载图像文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16739598/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com