Listing files available for download - files are stored in location accessible to the application only

此生再无相见时 提交于 2019-12-07 18:21:53

问题


I have a set of pdf files stored in the location accessible only by the application - so those files cannot be accessed directly via http.

The file paths are stored by the database and when the user is given the option to download a file the code as below is being executed:

 Response.ContentType = "Application/pdf"
 Response.AppendHeader("Content-Disposition", "attachment; filename=<some file name>")
 Response.TransmitFile(Server.MapPath("<the file path>"))
 Response.End()

It all works fine provided I am dealing with a single file

The problem:

I have a stored procedure that returns a list of all the files available to the user for download, and it can return any number of files ranging from 1 to 20.

I would like to create a page that would list all those files along with the download option next to each file.

Something like

File name 1, some description 1, download (button, link?)
File name 2, some description 2, download (button, link?)

It cannot be simply an url link because as I mentioned the files are not directly accessible and some code needs to be executed for each download

What would an elegant solution to accomplish this using .net2.0?


回答1:


With regular ASP.NET (2.0) you would want to create a "handler". The easiest option is to add a "generic handler" (ashx) template - then put a regular link on the page to (for example) "download.ashx?id=2".

Inside the handler, parse the query-string, and stream the file to the user:

    public void ProcessRequest(HttpContext context)
    {
        // set headers...
        string filePath = FindPath(context.Request.QueryString("id"));
        context.Response.WriteFile(filePath);
    }

where FindPath resolves the physical file from the query-string link.

If this was ASP.NET MVC, you could just use the File(path) action-result.




回答2:


The URLs in the list of files your return to the user can point to an ASPX page that can download them just like in the example code you provided.



来源:https://stackoverflow.com/questions/532379/listing-files-available-for-download-files-are-stored-in-location-accessible-t

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!