保护下载文件





3.00/5 (6投票s)
2007 年 11 月 27 日
2分钟阅读

59250
保护上传的文件安全,防止用户通过完整路径下载
引言
有时你可能需要保护文件下载,只允许已登录的用户下载。但如果用户知道完整的 URL,他们就可以下载你的文件。本文将帮助你保护 Web 应用程序中的文件夹里的文件。
(图 1)
背景
只允许用户上传文件,但不能直接通过完整的 URL 下载,例如:
https:///Development/upload/uploads/document.pdf
1. 首先你需要创建一个 Web 应用程序
2. 创建一个你想上传文件的文件夹,在本例中我将使用 UPLOADS
3. 在 IIS 中,进入你的应用程序,并选择 UPLOADS 文件夹
4. 右键单击并选择属性
5. 选择“目录”选项卡,确保只选择“允许写入”权限。此步骤将允许你将文件上传到此文件夹。
如果用户尝试通过输入完整的 URL 获取文件,他们将收到一个错误(见图 1)
6. 插入一个链接按钮或按钮(或者你想要通过任何方式下载)
7. 在 web.config 中插入以下内容(如果你不想硬编码目录):
<appSettings> <add key="uploadDirectory" value="uploads" /> </appSettings>
8. 然后,你只需要编写下载函数。(参见使用代码部分)
使用代码
关于如何使用文章或代码的简要说明。类名、方法和属性,任何技巧或窍门。
代码块应设置为“Formatted”样式,如下所示
Private Sub LinkButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkButton1.Click
downloadfile("document.pdf") '
End Sub
'This is the function that you have to use
Private Function downloadfile(ByVal strFile As String)
Dim fs As FileStream
Dim strContentType As String
' This is the important part, because you going to use the local path
'to get the file
Dim strPath = Me.Server.MapPath(System.Configuration.ConfigurationSettings.AppSettings("uploadDirectory")) & "\"
Dim strFileName As String = strFile
fs = File.Open(strPath & strFileName, FileMode.Open)
Dim bytBytes(fs.Length) As Byte
fs.Read(bytBytes, 0, fs.Length)
fs.Close()
Response.AddHeader("Content-disposition","attachment; filename=" & strFileName)
Response.ContentType = "application/octet-stream"
Response.BinaryWrite(bytBytes)
Response.End()
Return True
End Function
我用 300 MB 的文件测试了这个函数,它工作正常!但用 650 MB 的文件,我们遇到了一些问题(内存问题)。
如果一切正常,你应该看到这个屏幕
关注点
要将文件上传到你的网站,请遵循这些链接,这是我之前制作的另一个函数
并且可能有所帮助... (cruzagr3 源代码)
http://www.soloasp.com.ar/vermensaje2.asp?idmensaje=23643&idforo=3
历史
我将很快添加更多内容...