Send XML File to client - asp.net

I have an XDocument object that needs to be downloaded by the client. This xml will be generated on page_load and then sent to the user as a download.
I cant figgure out how to send the object to the client without having an acctual file.
Any ideas?

As stated i checked this other post not quite the same but close enough.
Response.Clear();
Response.ContentType = "text/xml";
Response.AppendHeader("Content-Disposition","attachment;filename=" + DateTime.Now+".xml");
Response.Write(doc.ToString());
Response.End();

Related

Asp.Net 6.0 Redirect user to a URL containing json content and start download

I have a scenario where the user passes a fileName to download.
We don't download the file on the server and stream back to the user because of bandwidth restrictions
We get the file path to download, and redirect to the location where the json file would be hosted
[Route("[controller]/DownloadJsonFile")]
public async Task DownloadJsonFile(string fileName)
{
//Get the file name
string fileToDownload = "https://hostedfilelocation/....test.json"
Response.Redirect(fileToDownload);
}
Currently, this method ends up rendering the Json content on the browser.
Is there a way so that the browser can start automatically downloading the file?
That way it wouldn't take super long to render the file on the browser.
P.S. If the file is of type zip or gzip, it is not rendered on the browser but rather is automatically downloaded.
The application is a .Net 6 Asp.Net MVC application
I have tried the below code but the behavior is the same but it renders json on the browser instead of downloading it.
string fileToDownload = "https://hostedfilelocation/....test.json"
HttpResponse response = HttpContext.Response;
response.Clear();
response.ContentType = "application/octet-stream";
response.Headers.Add("Content-Disposition", "attachment; filename=" + fileName);
Response.Redirect(fileToDownload);
The approaches mentioned in this blog post are all mentioning rendering the file in an iframe but I want the download happen on the client side.
Download File via browser redirect
If you want to download it directly, add the download attribute:
<a class='download-file-link' target='_blank' href='DownloadJsonFile' download="somefilename">

Execute code after Excel Download in ASP.NET

I'm having a piece of code which downloads excel of Invalid records after Import.
I want to refresh a grid after this kind of partial successful import. But, code after excel auto download is not executing.
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + PathToExcelFile);
Response.AddHeader("Content-Type", "application/Excel");
Response.AddHeader("Content-Length", file.Length.ToString());
Response.WriteFile(file.FullName);
HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
HttpContext.Current.Response.SuppressContent = true; // Gets or sets a value indicating whether to send HTTP content to the client.
HttpContext.Current.ApplicationInstance.CompleteRequest();
I had found that Response.Flush() will throw an Thread Abort exception. Hence changed it to CompleteRequest(). But, still no luck.
Not sure what I'm doing wrong?
Save the file name/path etc. to ViewState variables, then call window.open to a separate download.aspx page which processes the downloading of the file. In the Download page reference the ViewState variables you previously set. In the original (not the download) page you can execute what ever code you like after the window.open call.

Updating a page before initiating a download?

I've got a page that allows users to enter search criteria and then display matching records. It also has a download button to enable the user to download matching records.
How can I code it so that clicking on "Download" will first refresh the record display before downloading the data?
This is the code that I'm using for the download:
Response.ClearContent();
Response.ClearHeaders();
using (MemoryStream outputStream = new MemoryStream())
{
// some details elided...
outputStream.Write(documentData, 0, documentData.Count());
string fileName = GenerateFileName();
Response.AppendHeader("content-disposition", String.Format("attachment; filename={0}", fileName));
outputStream.Flush();
outputStream.WriteTo(Response.OutputStream);
}
Response.Flush();
Response.Close();
Only one response you can send back to the browser, ether you update the data, ether you send the new header to start the download.
To make both of them you need to change your steps probably using some javascript and/or ajax call.
How HTTP protocol works: http://www.w3.org/Protocols/rfc2616/rfc2616-sec1.html
Construct a javascript method that first updates the page via AJAX, then proceeds to make a non-AJAX request to download the file. As Aristos says, this cannot be done in a single request. A different solution could be to download the file first (non-ajax), then refresh the page without ajax. Normally, javascript code cannot be executed correctly after a new non-ajax request is made, but if it only downloads a file, I think the code might continue its execution to post the next request.

Mail Attachment in ASP.net

Am trying to add an attachment to mail in asp.net VB.
I could send mail fine until I added the attachment code,
Dim attch As Attachment = New Attachment("http://sitehere.com/Documents/file.jpg")
mail.Attachments.Add(attch)
I am getting the error URI formats are not supported.
Any ideas why that is and what I can do about it?
The Attachment class expects either a path to a file on the file system, or a Stream.
Try:
Dim data As Byte() = New WebClient().DownloadData("http://sitehere.com/Documents/file.jpg")
Dim attachment As New Attachment(New MemoryStream(data), "file.jpg")
That's me doing my best to translate from C# to VB.NET so the syntax might not be 100% correct, but that's the general idea. That will download the data into a byte array, then create a memory stream from those bytes and pass that to the Attachment constructor.
You can't add an attachment straight from a URL. You'll need to download the file first, then add it as an attachment.
you can use HttpWebRequest to get the file as a stream, then attach the stream. That saves having to store the file on disk.
If you have the file locally in your server and in a folder which you know the path, dont use the uri for that,
Dim eMessage As New MailMessage
Dim attachLabel As Attachment
Dim location As String
loction= Server.MapPath("Documents\\file.jpg")
attachLabel = New Attachment(loction)
eMessage .Attachments.Add(attachLabel);
If you really want to send a file from another url, you may use HttpWebRequest to download that first and send it as Colin and Davy8 metnioned.

IIS7 downloading file length

I've following code for file download:
FileInfo fileInfo = new FileInfo(filePath);
context.Response.Clear();
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + System.IO.Path.GetFileName(filePath));
context.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
context.Response.WriteFile(filePath);
context.Response.End();
When I run it on my local IIS6 it works fine. Web browser (tested on IE8, Firefox 3.5.2, Opera 10) shows file length before I start download the file.
When I run this code on remote IIS7, web browser doesn't shows file length. File length is unknown.
Why I don't get file length when this code runs under IIS7?
Use Fiddler to check what is actually sent. My guess is you are getting chunked encoding as a result of buffering being set to false on the IIS7 server.
BTW, drop the Response.End call its quite a traumatic thing to do and is unnecessary (for that matter so is the call to Clear).
Edit
Strictly speaking when streaming content with chunked encoding (which is desirable in your scenario) the Content-Length header ought not be present (see RFC2616 Section 4.4.) It seems to me that IIS7 takes it upon itself to enforce this. In fact I've had a Classic-ASP scenario in which IIS7 throws an error when COM code tries to add a Content-Length header when buffering is off.
This is really annoying because despite what the committee in the ivory towers would like, this header give the end user a very useful piece of info.
Thanks for this post.... I got it working for IE with the first line.
public void WriteCSV(string strData) {
//Required for IIs7 WS2008R2 fix
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/csv";
Response.AddHeader("Content-Disposition", "attachment;filename=report.csv");
Response.Write(strData);
Response.Flush();
Response.End();
}

Resources