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

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

Related

How to retrieve asp.net media / resources based on logged in user?

I have an asp.net web api project using token based authentication. my app uploaded and retrieve images and I keep file path in table_myfiles along with the uploaded user ID.
I would like the user to access only the files he have uploaded, which I can identify from the table.
How to protect my resources to restrict access to only to the user based on table_myfile ? And not to anyone without logging in or direct link / path ?
I have been searching for any possible solution for a week now , I think I should implement a middleware to manage access. But I couldn’t find any resources on how to implement the same.
Currently my api shows all resources just by directly accessing the file path/link.
The simple apporach is to remove the vitural folder, or that folders from the web site folders. That way, no simple URL exists for any of the files.
So, for a user to get/see/use/download a file? You present say a listview or some kind of grid (or repeater) that displays and lists out the files.
Then, when they want to download or view a file?
You use response.write and stream the file down to the client side.
Remember, on the server, code behind uses 100% clean and correct windows file paths. For any web based URL, then that folder must be in a valid path of the web site. When they type in a valid URL, it eventually gets translated to that given folder in the site (or a external folder provided when you create a mapped "virtual" folder in IIS. However, if you don't provide that virtual folder, or the folder is NOT in the web site file/folder sets, then no valid URL's exist. However, that folder can be directly used and hit with code behind - any valid server path/folder name is allowed in code behind.
Because when streaming the file, you need path name, file name, AND ALSO the "mine" type. Thankfully, .net 4.5 or later has this ability.
so, from a database (table) I display the file names like this:
But, if you click on the preview image, that is a image button.
The code behind simply gets/grabs the file name from the database.
I then download (stream) the file to the browser side like this:
if (File.Exists(strInternalFullPath))
{
string strConType = MimeMapping.GetMimeMapping(strInternalFullPath);
binFile = File.ReadAllBytes(strInternalFullPath);
Response.ContentType = strConType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(strWebUrl));
Response.BinaryWrite(binFile);
Response.End();
}
else
MyToast2(this, btnLink.ClientID.ToString, "File Not found", "We no longer have this file avaiable.");
so, this buttion behaves 100% like a link, but there are no existing URL's or path name that points to the files folder from a web based URL.
Remember:
Web based URLs - they auto map from the web site URL to a existing folder.
You can use server.MapPath("some url to file") to "translate" this to a internal file name.
Code based files:
In your .net code (code behind) ANY file name is a standard plane, jane file name that points to a file on the server.
so, once we have that file name from the database, you can steam the file as if the user clicked on a link. But you never have to expose the actual file name, or file path. And no such valid URL's exist on the web site, since you do NOT have that files folder in the web site folder hierarchy - but placed that folder outside of the web site.
As long as that folder is outside of the web folders, and as long as you don't setup a virtual folder that points to that folder outside the web folders?
Then code behind can STILL get/grab/see/use any file on the server. that code uses a full valid windows file name, - but the web site will have no mapping to such a folder - hence no valid URL's will exist or can be typed in.

Download a file on the client macine using asp.net

I want to download a text file from my website to the users pc without prompting him for the location to save the file.
I have tried it using code below :
Response.TransmitFile("G:\Medical Reporting\Medical\Users\Vishal\Uploaded\Key.txt")
Response.End()
But every time I am just redirected to the new page and all the contents of the file is written there. I don't want to display the contents of the file, but I want to download the file.
Not possible - it's a security issue, otherwise the world would be trying to save all sorts of files on a users machine.
If it's an intranet each user could have a shared drive on a network accessible to the web app and simply copy the file using IO.File.Copy method.
Update
To Prompt a user to download a file you can use the following code which will be fired after clicking something like a button:
this example is for an image, though you can just change the ContentType filename to suit your needs.
Response.ContentType = "image/jpeg";
// this is the important bit that gives the user the prompt to save
Response.AppendHeader("Content-Disposition","attachment; filename=yourfile.jpg");
Response.TransmitFile(Server.MapPath("~/yourfile.jpg"));
Response.End();

Displaying Save File Dialog in Asp.net web page

I have a ASP.net page which writes a file to the local disk.
I want to present the user a Save File dialog box and allow him to set the path to the folder.
I know code like below can be used;
Response.Clear();
Response.ContentType = "text/csv";
Response.AddHeader( "Content-Disposition", "attachment;filename=\"report.csv\"" );
// write your CSV data to Response.OutputStream here
Response.End();
But it fixes filepath.
I need to capture the filepath that the user selects.
Is that possible in ASP.net?
Thanks.
it does not work like that from a web page, you have to initiate the download suggestiong a target file name then the user can override your suggested file name and select any folder or filename he likes and your content will be saved in that location.
you do nothing with a local path which only makes sense on the client machine on the server side of ASP.NET application.
I need to capture the filepath that the user selects. Is that possible
No. Your web server presents a file to the client, where the client has the option to save this file.
In what way would the path the client saves this file be interesting to the server?

download option window in jsp

I need to give an option to user in jsp to choose a folder where he can save/download a file. Please help me on the same.
the text input="file" will give the file chooser but i need the directory chooser
HTTP doesn't allow you to specify (server side) where a file is downloaded to - this is not a jsp specific thing.
If you need to this then you'd need to provide an embedable application (javascript, java, flash, vbscript...) which is allowed to operate outside the browser sandbox and implements its own network client for retrieving the file. Which is far from an ideal solution.
You can force the download to use a specific name via the content disposition header.
the text input="file" will give the file chooser
..but that's for uploads - not downloads.
You can't set folder location at client machine of downloaded file using JSP/Servlet. If you want to add folder chooser feature then you have to develop an applet. You may use JFileChooser to allow user to select a folder and java.net.URL and java.net.URLConnection to download a file.
Most browsers will automatically download a file that the browser doesn't render, so it's just a link...! For example, if it's a zip file, just add it as any old "a link" in your code. When the user clicks , the download/save dialog will be launched ....
The "save/download" feature is a client issue -remember the web developers job is to provide content- it's the browser that decides how to deal with the content.
The key is the Content-Disposition header. Its value has to be set to attachment to force a Save As dialogue. You can do this job in a servlet. Just let your link URL point to a file servlet like so
download filename.ext
Then, in the file servlet, which is for the above example to be mapped on an URL pattern of /fileservlet/*, do the following:
String filename = URLDecoder.decode(request.getPathInfo().substring(1), "UTF-8");
response.setHeader("Content-Type", getServletContext().getMimeType(filename));
response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
// Now get an InputStream of the file and write it to OutputStream of response.
See also:
Simplest way to serve static data from outside the application server in a Java web application

How to get a file from a Database and put it in an FTP?

I have an aspx page that gets a list of documents available in a database through a DataGridview and I want that when the users clicks on the link of the document he want's to sent it as an FTP or HTTP document, like if it was on a drive on the server.
The problema I have is that I know that when the file is on a drive it is easy but if it is on the database I do not know how to serve it to the web page user.
I thougth maybe that when de user clicks on the link to save the file to a temp directory, and then redirect the page to that page with the name of the file, but I do not know if it is to much of a touble and there is a better way. Of course if I do this I will have to delete the file from the drive after it has been downloaded.
I get the way to do this, is just a matter of use
Response.ContentType = "image/jpeg";
Response.AppendHeader("Content-Disposition", "attachment; filename=SailBig.jpg");
//Response.BinaryWrite(foto);
Response.OutputStream.Write(foto, 0, foto.Length);
The file, is in binary.

Resources