ASP.NET Meta refresh Force Download - c#

I am using a meta refresh tag to point to a file that i want to download from a server. How do i make it so that it downloads all files, rather than opens them in the browser. I am adding the meta tag in code behind like this:
String filename = filenode.Element("name").Value.ToString();
HtmlMeta redirectMetaTag = new HtmlMeta();
redirectMetaTag.HttpEquiv = "Refresh";
redirectMetaTag.Content = string.Format("2;url=http://example.example.net/example/" + filename);
this.Header.Controls.Add(redirectMetaTag);
At the moment, thie file eg a jpg is just being opened in the browser

If you want to force the browser to open a Save As dialog you must add a couple of custom headers for the page.
I sugggest you to use the TransmitFile function:
Response.ContentType = "image/jpeg";
Response.AppendHeader("Content-Disposition","attachment; filename=[your-file-name]");
Response.TransmitFile( Server.MapPath("~/images/[your-file-name]") );
Response.End();
It will automatically write the file content to the OutputStream of the Response.

Related

itextsharp open pdf with another browser windows

basically below is the code for me to read pdf file, the output for this code below is ask client to download the pdf file and open it from client side, this is not what i want,what i want it open the pdf at another browswer windows or open in inside tag under same browser windows, but how can i make it?
var fi = new FileInfo(Server.MapPath(#"~/AIA2.pdf"));
Response.Clear();
Response.AddHeader("Content-Disposition",
String.Format("attachment; filename=\"{0}\"",
"AIA2.pdf"));
Response.AddHeader("Content-Length", fi.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(fi.FullName);
Response.End();
This is not upto the server to decide how content is handled - content disposition could be set to attachment or inline but its to the handling application to process these and i do not think any browser does that.
I can suggest a two step solution for this:
Use inline; instead of attachment
On the client side (if you have control on that ofcourse), use something like
That should do the trick!

How To: Dynamically Creating the XML file content and sending as a text file in asp.net c#

hi there i am working on an asp.net web page that first lets users to enter required values to indicated textfields and then generate a new text file according to the data given by the user.
I want to let users receive a "Result.xml" file when they click on "get file" button.
i've searched for that info, i know it must have an easy solution but by now i am out of luck (i must be tired). i tried the following code but it didnt worked:
DataSet ds = new DataSet();
ds.Tables.Add("TEST");
ds.writexml("test.xml");
Response.TransmitFile("test.xml");
but the program says it couldnt find any file. also i dont want to "write" a physical file to the server, i just want to send the contents of the dataset as "test.xml"
Please help,
Thanks for spending your time.
Well assuming you are able to populate your DataSet properly, you should be able to use DataSet.WriteXML as in your example to write to a MemoryStream, then dump the file to the HTTP response without ever hitting your server's disk.
I'm a little rusty with C#, this example is from VB, so please take syntax with a grain of salt:
System.IO.MemoryStream objStream = new System.IO.MemoryStream();
System.Data.DataSet ds = new System.Data.DataSet();
ds.Tables.Add("TEST");
ds.WriteXml(objStream);
Response.Clear();
Response.Buffer = true;
Response.ContentType = "text/xml";
Response.AddHeader("Content-Disposition", "attachment; filename=File.xml");
Response.BinaryWrite(objStream.ToArray());
Response.End();
You can use the below code to write a XML file to the Client machine. Here we
write the contents directly into the Response.OutputStream using the XmlTextWriter:
try
{
Response.Clear();
Response.ContentType = "text/xml";
Response.AppendHeader("Content-Disposition","attachment;filename=FileName.xml");
XmlTextWriter xWriter = new XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8);
xWriter.Formatting = Formatting.Indented;
xWriter.WriteStartDocument();
//Create Parent element
xWriter.WriteStartElement("Parent");
//Create Child elements
xWriter.WriteStartElement("Element");
xWriter.WriteElementString("ID", "1001");
xWriter.WriteElementString("Name", "John");
xWriter.WriteElementString("Age", "22");
xWriter.WriteEndElement();
//End writing top element and XML document
xWriter.WriteEndElement();
xWriter.WriteEndDocument();
xWriter.Close();
Response.End();
}
Whenever you work with files in Asp.Net you should use Server.MapPath. If you use relative paths your code will probably try to write to the IIS folder and might (hopefully) not be allowed to do so. So instead of using "test.xml" you should use
Server.MapPath("~/text.xml")
The tilde expands to your web application folder. That said it's a bad idea to store the file to disc. The Response object has an OutputStream which can be used to send data to the browser. You should write your data set directly into that stream. So no file has to be written to disc, you don't have to care about paths and your code will also work with multiple concurrent requests.
You can have the link link to an IHTTPHandler with the folowing code:
public class YourHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Response.Clear();
Response.ContentType = "text/xml";
Response.AppendHeader("Content-Disposition", String.Format("attachment;filename={0}", XML_FileName));
Response.TransmitFile(Server.MapPath("MyFile.xml"));
Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}

ASHX Image Download on Click

I am using ashx to serve images from a database, is there anyway to have a user click on a link that allows them to download the file on the computer. (IE it shows the Save Dialog) Like you download a file. Is this possible to do?
If you want it to prompt to save make sure you add the following line when creating the response:
context.Response.AppendHeader("Content-Disposition",
"attachment;filename=" + filename);
This will make the browser treat it like an attachment and prompt with the save dialog.
EDIT: Based on your comment make sure you are building your response correctly:
// set attachment header like above
// then you need to get your file in byte[] form
byte[] dataYouWantToServeUp = GetData();
// you can set content type as well
yourHttpContext.Response.ContentType = "image/jpg";
// serve up the response
yourHttpContext.Response.BinaryWrite(dataYouWantToServeUp);
I think that if the navigator is able to open type of the file you're trying to get, It will open it without asking. If for instants, the file is in zip format, the navigator is not able to open it and will ask you to download it.

Download pdf programmatically

How can I download a PDF and store to disk using vb.NET or C#?
The URL (of the PDF) has some rediection going on before the final PDF is reached.
I tried the below but the PDF seems corrupted when I attempt to open locally,
Dim PdfFile As FileStream = File.OpenWrite(saveTo)
Dim PdfStream As MemoryStream = GetFileStream(pdfURL)
PdfStream.WriteTo(PdfFile)
PdfStream.Flush()
PdfStream.Close()
PdfFile.Flush()
PdfFile.Close()
You can try to use the WebClient (System.Net namespace) class to do this which will avoid any stream work on your side.
The following C# code grabs an IRS form and saves it to C:\Temp.pdf.
using(WebClient client = new WebClient())
{
client.DownloadFile("http://www.irs.gov/pub/irs-pdf/fw4.pdf", #"C:\Temp.pdf");
}
You can also try the following code sample to download pdf files
Response.ContentType = "Application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=Test_PDF.pdf");
Response.TransmitFile(Server.MapPath("~/Files/Test_PDF.pdf"));
Response.End();
How might you be able to use client.downloadfile when the URL is pointing a "showdocument.aspx" page.
Example:
https://gaming.nv.gov/modules/showdocument.aspx?documentid=246

How do I print an existing PDF from a code-behind page?

I've seen a few questions like this around SO but couldn't find anything that's right for me. The chain of events that I would like to occur is as follows:
User clicks an ASP.NET button control
This fires that button's onclick event, which is a function foo() in the C# codebehind
foo() calls some other (unimportant) function which creates a PDF which ends up saved to the server's disk. That function returns the path to the PDF
Without any other user interaction, once the PDF is generated, the print dialog box opens in the user's browser to print that PDF
What do I need to do to accomplish step 4? Ideally, it would be something I can call in foo(), passing in the path to the PDF, that will trigger the print dialog box in the user's browser (printing the PDF and not the page the from which the onclick fired).
I think that I might be able to forward to the URL of the PDF document, and embed some Javascript in the PDF that automatically prints it, but I would rather not - I don't necessarily want to print the PDF every time it's opened (in a browser). Any other good way to do this?
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=myfilename.pdf")
Response.ContentType = "application/pdf"
Response.BinaryWrite(ms.ToArray())
Where ms = a memorystream containing your file (you don't have to write it to disk in-between.)
Otherwise if you absolutely have to deal with coming from the hard disk, use:
Response.WriteFile("c:\pathtofile.pdf")
Thanks for the answer Vdex. Here is the iText/C# version.
PdfAction action = new PdfAction();
action.Put(new PdfName("Type"), new PdfName("Action"));
action.Put(new PdfName("S"), new PdfName("Named"));
action.Put(new PdfName("N"), new PdfName("Print"));
PdfReader reader = new PdfReader(ReportFile.FullFilePath(reportFile.FilePath));
PdfStamper stamper = new PdfStamper(reader, Response.OutputStream);
stamper.Writer.CloseStream = false;
stamper.Writer.SetOpenAction(action);
stamper.Close();
I did not try this, but it is an idea:
If you can read querystring parameters in javascript embedded in the PDF, then embed the javascript, and make the print function be conditional on a javascript parameter.
That way, if you redirect to, for instance, yourpdf.pdf?print, it will print, and if it is opened without the print parameter, it behaves as any other normal PDF would do.
If you want to go down the path of printing it as soon as it is opened:
There is a flag that you can insert into the PDF that forces it to open up the print dialog as soon as the PDF is opened. I did this ages ago using the abcpdf component in classic ASP, the code looked something like:
Set oDoc = Server.CreateObject("ABCpdf4.Doc")
oDoc.SetInfo oDoc.Root, "/OpenAction", "<< /Type /Action /S /Named /N /Print >>"
Obviously the code would look different depending on which PDF creation tool you are using...
The solution I arrived at was this:
Create a new ASP.NET web form (I called mine BinaryData.aspx) to serve as a placeholder for the PDF. In the code behind, the only method should be Page_Load, which looks like:
protected void Page_Load(object sender, System.EventArgs e)
{
//Set the appropriate ContentType.
Response.ContentType = "Application/pdf";
Response.AppendHeader("Pragma", "no-cache");
Response.AppendHeader("Cache-Control", "no-cache");
//Get the physical path to the file.
string FilePath = (string)Session["fileLocation"];
if ( FilePath != null )
{
string FileName = Path.GetFileName(FilePath);
Response.AppendHeader("Content-Disposition", "attachment; filename="+FileName);
//Write the file directly to the HTTP content output stream.
Response.WriteFile(FilePath);
Response.End();
}
}
The PDF is passed in to the page through the Session variable named "fileLocation". So, all I have to is set that variable, and then call Response.Redirect("BinaryData.aspx").
It doesn't automatically print, but it triggers the download of the PDF without leaving the current page (which is good enough for me).

Categories

Resources