Allow only Logged in user to download images - asp.net

I am working on an Application based on Monorails which generates images / charts at runtime. The code writes the images to OutputStreams and not to the Appserver hard drive. It allows the user to download the image. I want to make sure that only the logged in user is able to download the image and no one else.
For e.g if any user A tries to download image generated for user B user A should not be able to do that no matter what.
Note: I am not storing the file to the hard disk.
How can I implement this???
Below is the sample code I have written for the image download.
var stream = new MemoryStream();
Response.Clear();
Response.ContentType = "application/image";
Response.AddHeader("Content-Disposition","attachment; filename=" + imagefilename);
var array = stream.To Array();
Response. OutputStream.Write(array,0,array.length);
Response.End();
Please help me fix this issue.
Thanks,
Rahul

You need logic in the code to check if the user logged in 'owns' the image they are trying to download.
If they don't 'own' it, Response.End their request

Related

Saving a generated html document to specific folder in ASP.NET

So I have written a simple program that creates an html document based on user input into a number of fields. Currently, when the user pressed a button it generates the document and automatically downloads onto the user's machine using the following:
Response.ContentType = "text/plain";
Response.Write(HTML.ToString());
Response.Flush();
Response.End();
But, I would like to have the file written to a folder on the user's machine when a user presses a button. So, let's say I want them to press the button and it automatically writes the file to their desktop. What would this code look like? (c#)
Thank you,
p.s. I have been trying something like this with no luck:
string filename = Server.MapPath("~/C:/Users/Sean/Desktop/new.html");
System.IO.StreamWriter textWriter = default(System.IO.StreamWriter);
textWriter = System.IO.File.AppendText(filename);
textWriter.Write(HTML);
textWriter.Close();
Using ASP.Net, you CANNOT force user to save any file on any specific location. Moreover the file you want user to save is HTML which will be rendered directly on browser i.e. user will not be prompted to save it on their machine.
So to answer your question, you cannot have ANY file automatically saved to user's machine. There has to be some manual intervention by the user(to select the path at which he/she wants to save it.)

Retrieve image stored in in db and save to a file

I have a customer that is asking to be able to retrieve an image from a Sql Server Db and turn around and save it to a directory on his computer. He wants to be able to do this via a asp.net web page. I am able to retrieve the image from the image as a byte array but have no idea how to take that image and save it to the directory as a file. Anyone have any ideas on how to do this? Thanks.
You can try with Save Method
MemoryStream memoryStream = new MemoryStream((byte[])YourDataTable.Rows[0]["ImageData"]);
Picturebox picturebox = new Picturebox();
picturebox.Image = Image.FromStream(memoryStream);
picturebox.Image.Save("...YourPath", System.Drawing.Imaging.ImageFormat.Jpeg)

PDF from content of asp.net page

I'm trying to create a pdf of the content on a page ("returnsPage.aspx?id="returnId) and allow the user to download this directly when clicking the button.
However in my onClick method I have the following code:
lnkLoadPDF.CommandArgument = "/returns/returnsPage.aspx?id="+returnId.ToString();
string virtualPath = lnkLoadPDF.CommandArgument;
string fileName = System.IO.Path.GetFileName(virtualPath);
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.WriteFile(virtualPath);
Response.ContentType = "";
Response.End();
Response.Redirect("/returns/returnsPage.aspx?id="+returnId);
which returns this error:
'/returns/returnsPage.aspx?id=23' is not a valid virtual path.
Can anyone please tell me what I'm doing wrong?
Thanks!
In order to turn a webpage into a pdf, you must convert it to pdf on the server. In order to do that, you must have a program on the server that can do that for you.
I've tried a variety of webpage-to-pdf converters and one of the better ones is a free, open source program called wkhtmltopdf.
After you create the pdf, you can either redirect the user to the newly created pdf (discouraged), or prompt them to download it with a savefile dialog.
If you get stuck, just search for wkhtmltopdf on stackoverflow or post another question.
You can't send a file to the client and redirect him to a new location during the same request. You also can't create a PDF from a webpage without some kind of component that converts the HTML into a PDF, it's (quite a bit) more tricky that what I think you're trying to attempt.
As for your exception, are you sure returnsPage.aspx exists? :)

How to designate the name of a file that a user downloads via an ASHX downloader?

This is my first time writing code that allows a user to download a file uploaded by another user.
I've written an ASHX file, download.ashx, with code that looks like this:
s = context.Request.QueryString.ToString();
byte[] buffer = new ReplacementTicketFileIO().GetSpecifiedFile(s);
context.Response.BinaryWrite(buffer);
context.Response.Flush();
context.Response.End();
When a user clicks on a link to download.ashx with the appropriate querystring, the file is downloaded, but the browser wants to display the content in the browser window. If the user right-clicks on the link, he can download the file, but the name of the file defaults to download.ashx.
I would like to accomplish two things:
1) I would like to be able to specify the default name of the file downloaded on the user's device based on the querystring.
For instance, if the user clicks on download.ashx?linkedfile=car.pdf, I would like for the browser to default to car.pdf for the name of this file.
2) I would like for the browser to default to saving the link, as opposed to opening the link in the browser window.
Is it reasonable for me to want to do this, or is there a better way to download files? Please let me know.
Set the Content-Disposition HTTP header. E.g.
Content-Disposition: attachment; filename=hello.jpg
You can do that in C# using:
Response.AddHeader("Content-Disposition", "attachment; filename=hello.jpg");
Here is something I have for excel files and I believe it forces a download rather than a new window. There is a page property for QueryString. You would just need to capture the QueryString and use it in this code as well as determining the content type. The String.Format will give you clean code.
private string _ExcelFilename
{
get
{
return (Request.QueryString["xls"] != null) ? Request.QueryString"xls"] : "bis";
}
}
Page.Response.Clear();
Page.EnableViewState = false;
Page.Response.Clear();
Page.Response.ContentType = "application/vnd.ms-excel";
Page.Response.AppendHeader("Content-Disposition", String.Format("attachment; filename={0}_{1}.xls", _ExcelFilename, DateTime.Now.ToString("yyyyMMdd")));
Page.Response.Write(excel);
Page.Response.Flush();
Page.Response.End();

Response.WriteFile

There is one URL with specific syntax to download a file.
http://www.hddownloader.com/?url=http://www.youtube.com/watch?v=N-HbxNtY1g8&feature=featured&dldtype=128
The user enters the file name in the textbox and presses the download button.In the click event the Response.WriteFile is called which sends the file to the client.
Now I want to create another website with a page, in which the user enters the filename and presses the download button to download that file.
Now I want to utilise the first URL for that. I dont want to use Response.Redirect, because by that way, the user will come to know that I am using mydownload.com.
How can I acheieve that.
One way is : When we download something from microsoft's website, a small popup window(with no close, maximise and minimise button) and then the save dialog box appears.
How to achieve this or another to achieve the same ?
You could first download the file from the remote location on your server using WebClient.DownloadFile:
using (var client = new WebClient())
{
client.DownloadFile("http://remotedomain.com/somefile.pdf", "somefile.pdf");
Response.WriteFile("somefile.pdf");
}
or if you don't want to save the file temporary to the disk you could use the DownloadData method and then stream the buffer into the response.
UPDATE:
Example with the second method:
using (var client = new WebClient())
{
var buffer = client.DownloadData("http://remotedomain.com/somefile.pdf");
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment;filename=somefile.pdf");
Response.Clear();
Response.OutputStream.Write(buffer, 0, buffer.Length);
Response.Flush();
}

Resources