Download PDF into Webapplication(.Net) from SSRS URL access method - asp.net

I am trying to download a pdf file from SSRS server to my .net application. I am using URL access method to get byte data from the SSRS-URL (http://SsrsDevServer/ReportServer/Pages/ReportViewer.aspx?%2fMainFolder%2fReports%2fInvoice&rs:Command=Render&). My .net application code is shown below.
Note : by making Client.UseDefaultCredentials = true; and without credentials part, it works as expected only in my local machine, but failing when I published it to DEV server.
WebClient Client = new WebClient();
// Client.UseDefaultCredentials = true;
string strReportUser = "USERNAME";
string strReportUserPW = "PAssword";
string strReportUserDomain = "Domain";
Client.Credentials = new System.Net.NetworkCredential(
strReportUser,
strReportUserPW,
strReportUserDomain);
byte[] myDataBuffer = Client.DownloadData(theURL);
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=\"" + fileName + "\"");
Response.BinaryWrite(myDataBuffer);
Response.Flush();
Response.End();
Appreciate any help.
Thanks!

Related

How to download a file from sub domain which is available on domain in asp.net C#

How to download a file from sub domain which is available on domain in asp.net C Sharp
suppose I have a file abc.doc on example.com
but now I want to download this file abc.doc from admin.example.com ,
how it is possible in asp.net C sharp
I tried lots of code but it is showing is not a valid virtual path.
This is the code which I used.
string strURL = "`http://example.com/resume.doc`";
WebClient req = new WebClient();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.AddHeader("Content-Disposition", "attachment;filename=\"" + Server.MapPath(strURL) + "\"");
byte[] data = req.DownloadData(Server.MapPath(strURL));
response.BinaryWrite(data);
response.End();
You are using Server.MapPath on an URL. You can't do that since the URL isn't on your server file system. Remove that and you can download your file.
byte[] data = req.DownloadData(strURL);
Thanks for quick reply Mr. Sami , I have removed as you have suggested by it is showing error http://example.com/resume.doc is not a valid virtual path. My new code is string code is
string strURL = "http://example.com/resume.doc";
WebClient req = new WebClient();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.AddHeader("Content-Disposition", "attachment;filename=\"" + Server.MapPath(strURL) + "\"");
response.BinaryWrite(data);
response.End();

Returning a downloadable file using a stream in asp.net web forms

In asp.net MVC I can do something like the following which will open a stream:
Stream strm1 = GenerateReport(Id);
return File(strm1,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"Report_" + reportId.ToString() + ".xlsx");
Notice how I am passing strm1 which is a stream. I can then name it Report_+ ...xlsx like the example above shows.
Is there a similar way to do this with asp.net web forms using c#.
You can use TransmitFile or WriteFile if the file is in your website folder.
string fileName = string.Format("Report_{0}.xlsx", reportId);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition",
string.Format("attachment; filename={0}", fileName));
Response.TransmitFile(fileName);
Response.End();
Stream
If your data is already in Memory, you want this method which writes the response in chunks.
Stream stm1 = GenerateReport(Id);
Int16 bufferSize = 1024;
byte[] buffer = new byte[bufferSize + 1];
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition",
string.Format("attachment; filename=\"Report_{0}.xlsx\";", reportId));
Response.BufferOutput = false;
int count = stm1.Read(buffer, 0, bufferSize);
while (count > 0)
{
Response.OutputStream.Write(buffer, 0, count);
count = stm1.Read(buffer, 0, bufferSize);
}
I use this extension to send a stream as a downloadable file:
public static class ToDownloadExtention
{
public static void ToDownload(this Stream stream, string fileName, HttpResponse response)
{
response.Clear();
response.ContentType = "application/octet-stream";
response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
stream.CopyTo(response.OutputStream);
response.End();
}
}
And the usage is:
var stream = new MemoryStream();
stream.ToDownload("someFileName.ext",Response);
Or if you have a stream ready to be written, simply copy it to response stream:
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment; filename={your file name}");
Response.OutputStream.Write(stream, 0, stream.length);
Response.End();
Added same code just for visibility

Context.Response.Headers' threw an exception of type 'System.PlatformNotSupportedException

I'm trying to generate a PDF using a memory stream. When clears the headers, it threw Server cannot clear headers after HTTP headers have been sent. Here is my code snippet.
Context.Response.Clear();
Context.Response.ClearHeaders();
Context.Response.ClearContent();
System.IO.MemoryStream st = new System.IO.MemoryStream();
st = (MemoryStream)levyStream;
byte[] b = st.ToArray();
Context.Response.AppendHeader("Content-Disposition", "inline; filename="+MyFilename);
Context.Response.AppendHeader("Content-Length", b.Length.ToString());
Context.Response.BufferOutput = true;
Context.Response.ContentType = "application/pdf";
Context.Response.Charset = "";
Context.Response.OutputStream.Write(b, 0, (int)st.Length);
Context.Response.Flush();
st.Close();
I have attached an error in response object along with this.
Regards,
Aruna
It appears you are using IIS 7. If so, you need to change the application pool type from classic to integrated. The integrated pipeline mode is IIS 7 specific.

Server not pointing to folder

i have a website on server. It has a button which triggers the downloading of a file(.zip/.doc) from that server.
But it is not pointing to that folder/file. How to resolve this issue??
It fails at this particular file...
public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed){
FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
}
I have not tried your code but this seems to work for me. you can make the rest dynamic.
string FileName = "test.zip";
string PathFile = "C:\project\download\test.zip";
var fileInfo = new System.IO.FileInfo(PathFile);
Response.ContentType = "application/zip";
Response.AddHeader("Content-Disposition", String.Format("attachment;filename=\"{0}\"", FileName));
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.WriteFile(PathFile);
Response.End();

How can I prompt a user to open or save a PDF file returned by a .aspx file?

I have a Flex application that calls a .aspx page on our webserver, which builds a PDF or Excel File. Right now, I am using navigateToURL() to call the file, and this works fine when the output file is built successfully. However, if there is an error, or timeout, there is no way of knowing this in the Flash movie.
I am trying to use URLLoader instead, so that I can listen for an HTTP Status Code, and know when the load is complete, however, the URLLoader simply returns the bitmap data, with nothing prompting the user to open or save the output file. Is there anyway to do this?
Here are both versions of my ActionScript code:
private function buildFile():void
{
var variables:URLVariables = new URLVariables();
variables.rptName = "report1";
variables.rptFormat = "PDF";
var request:URLRequest = new URLRequest();
request.url = "/buildFile.aspx";
request.method = URLRequestMethod.POST;
request.data = variables;
var loader:URLLoader = new URLLoader();
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS,
httpStatusHandler);
loader.load(request);
}
private function buildFile():void
{
var variables:URLVariables = new URLVariables();
variables.rptName = "report1";
variables.rptFormat = "PDF";
var request:URLRequest = new URLRequest();
request.url = "/buildFile.aspx";
request.method = URLRequestMethod.POST;
request.data = variables;
navigateToURL(request, "_self");
}
FYI, here is the block of code that currently outputs the PDF or Excel file:
System.Web.HttpContext httpC;
httpC = System.Web.HttpContext.Current;
httpC.Response.Clear();
httpC.Response.ClearHeaders();
httpC.Response.Expires = 0;
switch (ReportFormat)
{
case "Excel": Response.ContentType = "application/vnd.ms-excel"; break;
case "PDF": Response.ContentType = "application/pdf"; ; break;
}
Response.AddHeader("Content-disposition", "attachment;filename=" + fileName);
BinaryWriter binaryWriter = new BinaryWriter(httpC.Response.OutputStream);
binaryWriter.Write(result);
You server should send "application/octet-stream" header when user requests that PSD file.
With ASP.NET it could look like this:
Response.ClearContent();
Response.ClearHeaders();
// with this header user will be promted to open or download file
Response.ContentType = "application/octet-stream";
// with this header, you will suggest to save file with "test.pdf" name
Response.AddHeader("Content-Disposition", "attachment; filename=test.pdf");
Response.WriteFile(Server.MapPath("~/test.pdf"));
Response.Flush();
Response.Close();
Also take a look here: Downloading files in Flex using the FileReference class
Also set the content-disposition to "attachment" in the aspx page.

Resources