Recently, code writing requires file permission management, which can be implemented through a custom HttpHandler. However
When downloading a file, modify the file name. For example, if the file stored on the server is a file named ab739s48fssa.txt
But the user downloads readme.txt. I checked it online for half a day, but the implementation is actually very simple. below is the implementation
Step.
First, you must define the custom HttpHandler in web. config: <Add verb = "*" path = "Attachments/*. *" type = "AttachmentHandler"/>
</HttpHandlers>
Then implement the custom AttchmentHandler class: Imports Microsoft. VisualBasic
Imports System. Data
Imports System. Data. SQL
Imports System. Data. SqlClient
Imports System. Diagnostics
Imports System. IO
Public Class AttachmentHandlerClass AttachmentHandler
Implements IHttpHandler
Public ReadOnly Property IsReusable () As Boolean Implements System. Web. IHttpHandler. IsReusable
Get
Return True
End Get
End Property
Public Sub ProcessRequest () Sub ProcessRequest (ByVal context As System. Web. HttpContext) Implements System. Web. IHttpHandler. ProcessRequest
'Determine whether the user passes Verification
If (context. User. Identity. IsAuthenticated) Then
Dim splitter As String () = context. Request. FilePath. Split ("/")
'Get the file name selected for download
Dim filename As String = splitter (UBound (splitter ))
'Get the full file path name
Dim fullfilename As String = context. Server. MapPath (context. Request. FilePath)
'Specifies the file name when the user downloads
Dim orifilename As String = "readme.txt"
'Obtain the file type
Dim strContentType As String = GetFileContentType (filename)
Context. Response. ContentType = strContentType
Context. Response. AppendHeader ("content-disposition", "attachment; filename =" + orifilename)
'Read file content to byte array
Dim file As FileStream = _
New FileStream (fullfilename, FileMode. Open, FileAccess. Read)
Dim buff (file. Length) As Byte
File. Read (buff, 0, buff. Length)
'Output the content in the byte array to the output cache.
Context. Response. OutputStream. Write (buff, 0, buff. Length)
Else
Context. Response. Redirect ("Login. aspx ")
End If
End Sub
End Class
The key to renaming a file is to add it to the Response header:
Context. Response. AppendHeader ("content-disposition", "attachment; filename =" + orifilename)
Here, orifilename is the file name that you want to see.