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.
- 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)
- 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.
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.