Create temporary link for download

后端 未结 5 1536
一向
一向 2020-12-08 18:04

I use ASP.NET
I need to give user temporary link for downloading file from server.
It should be a temporary link (page), which is available for a short time (12 hour

5条回答
  •  无人及你
    2020-12-08 18:35

    llya

    I'll assume you're not requiring any authentication and security isn't an issue - that is if anyone gets the URL they will also beable to download the file.

    Personally I'd create a HttpHandler and then create some unique string that you can append to the URL.

    Then within the ProcessRequest void test the encoded param to see if it's still viable (with in your specified time-frame) if so use BinaryWrite to render the File or if not you can render some HTML using Response.Write("Expired")

    Something like :

    public class TimeHandler : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest ( HttpContext context )
        {
        
            if( this.my_check_has_expired( this.Context.Request.Params["my_token"] ) )
            {
                // Has Expired 
    
                context.Response.Write( "URL Has Expired" );
                return;
            }
    
            // Render the File
            Stream stream = new FileStream( File_Name , FileMode.Open );
    
            /* read the bytes from the file */
            byte[] aBytes = new byte[(int)oStream.Length];
            stream.Read( aBytes, 0, (int)oStream.Length );
            stream.Close( ); 
    
            // Set Headers
            context.Response.AddHeader( "Content-Length", aBytes.Length.ToString( ) );
            // ContentType needs to be set also you can force Save As if you require
    
            // Send the buffer
            context.Response.BinaryWrite( aBytes );                            
    
        }
    }
    

    You need to then setup the Handler in IIS, but that a bit different depending on the version you're using.

提交回复
热议问题