Asp.net - Prevent file (PDF, Word) download from a particular folder

I am creating a recruitment site and have a folder called /CV/ where I am storing resume files uploaded by the member.

Lets say a user saves their resume and its called 123.pdf and is stored in cv/123.pdf. How can I prevent the pdf file from loading in the browser window or downloading to the users machine if they type in 'http://mydomain.com/cv/123.pdf'?

I am using forms Authentication, Asp.Net Membership and Roles Providers, Asp.net 4 on an IIS6 server.

Answers


  1. Create a folder that is outside of the hierarchy of the main www folder used by the site (so it cannot be directly accessed through url)
  2. Use an ashx handler to provide access to download the file. The logic within the ashx file can validate whether the user is authorized to download the file or not.

ASHX references: 1, 2, 3


The best way would be to put the files somewhere else, and write some code to access them -- then that code can verify whether the caller has the necessary rights.

For instance, you may store files in your /uploads/xyz123/ directory. Then in order to download a file, say myresume.pdf, the user would have to surf to http://yourserver/download.aspx?file=myresume.pdf.

That page then does the necessary validations, loads the file and outputs it as a binary to the browser, like so:

Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=" + filename);
Response.AddHeader("content-length", binaryStream.Length.ToString);
Response.BinaryWrite(binaryStream.ToArray());
Response.Flush();
Response.End();

No user will ever find out where the files are actually stored.


You can simple save the file in a directory that is not part of your web application.

If you want to store a file that should not be reached via http, do it this way.


Need Your Help

state_machine gem how to use transition_for

ruby state-machines

I would like to use transition_for of state_machine gem but the docs does not show which object I am supposed to use:

Single quotes in SQL in a Query Object inside of cfscript in a ColdFusion component

coldfusion hql cfc

A bit of a confusing title, but I'll try to be clear here. When using the query object inside of <cfscript> and you have some sql in the form:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.