Unable to download the PDF file from URL - c#

I need to download an .PDF file from a website : https://XXXXX/XXXX/XXXXXXX.pdf when user click's on link button. Below code is working fine in local but when I try to click on link button for downloading the file after deploying into server, First time it is working fire but next consecutive downloads, It is displaying as The XXXX.PDF download was interrupted or file cannot be downloaded.
try
{
string fullFileName =string.Empty;
LinkButton btn = (LinkButton)(sender);
string filepath = btn.CommandArgument;
string fileName = btn.Text;
if (fileName != null && !string.IsNullOrEmpty(fileName))
{
fullFileName = filePath +fileName ;
int bytesToRead = 10000;
// Buffer to read bytes in chunk size specified above
byte[] buffer = new Byte[bytesToRead];
//string fileName = System.IO.Path.GetFileName(fullFileName);
//Create a WebRequest to get the file
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | System.Net.SecurityProtocolType.Tls | (SecurityProtocolType)768/*TLS1.1*/ | (SecurityProtocolType)3072/*TLS1.2*/;
HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(fullFileName);
//Create a response for this request
HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();
if (fileReq.ContentLength > 0)
fileResp.ContentLength = fileReq.ContentLength;
//Get the Stream returned from the response
stream = fileResp.GetResponseStream();
// prepare the response to the client. resp is the client Response
var resp = HttpContext.Current.Response;
//Indicate the type of data being sent
resp.ContentType = "application/PDF";
//Name the file
resp.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
int length;
do
{
// Verify that the client is connected.
if (resp.IsClientConnected)
{
// Read data into the buffer.
length = stream.Read(buffer, 0, bytesToRead);
// and write it out to the response's output stream
resp.OutputStream.Write(buffer, 0, length);
// Flush the data
resp.Flush();
//Clear the buffer
buffer = new Byte[bytesToRead];
}
else
{
// cancel the download if client has disconnected
length = -1;
}
} while (length > 0); //Repeat until no data is read
}
else
{
lblFile.Text = "File Name is missing";
lblFile.Visible = true;
}
}
catch (Exception ex)
{
}
finally
{
if (stream != null)
{
//Close the input stream
stream.Close();
}
}
Can someone please guide me why it is failing in server

Related

Intercepting requested file path & Open file from different source in new tab

I have 4.7.2 application where on anchor tag we have file link like 'www.abc.com/a.txt'. If I click it file is opening in new tab.
But now expected result is - When user hit that link, I want to intercept this link & change it to 'www.xyz.com/a.txt' & return response in new tab. Basically open file in new tab (no download).
Currently I'm able to download file using below code but I want to open in new tab.
Stream stream = null;
int bytesToRead = 10000;
byte[] buffer = new Byte[bytesToRead];
try
{
string apiGatewayFilePath = "www.xyz.com/a.txt";
HttpWebRequest fileReq = (HttpWebRequest)WebRequest.Create(apiGatewayFilePath);
string fileName = Path.GetFileName(apiGatewayFilePath);
HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();
if (fileReq.ContentLength > 0)
fileResp.ContentLength = fileReq.ContentLength;
stream = fileResp.GetResponseStream();
var resp = HttpContext.Current.Response;
resp.ContentType = MediaTypeNames.Application.Octet;
resp.AddHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");
resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
int length;
do
{
if (resp.IsClientConnected)
{
length = stream.Read(buffer, 0, bytesToRead);
resp.OutputStream.Write(buffer, 0, length);
resp.Flush();
buffer = new Byte[bytesToRead];
}
else
{
length = -1;
}
} while (length > 0);
}
finally
{
if (stream != null)
{
stream.Close();
}
}

Can't seek audio files prepared with HTTP source (Android MediaPlayer)

So I'm trying to build some sort of a media player, the application prepares audio from an external source (HTTP server sitting on another device), when trying to seek the MediaPlayer returns "Stream has no duration and is therefore not seekable"
Note: I saw questions about the same error but they were about live streams, this is a static MP3 file.
Code from the other device (the server of the audio files)
private static void WriteFile(HttpListenerContext ctx, Android.Net.Uri uri, Activity activity)
{
var response = ctx.Response;
Debug.Print(ctx.Request.RemoteEndPoint.ToString());
using (var file = activity.ContentResolver.OpenInputStream(uri))
{
string fileName = "Audio.mp3";
ICursor cursor = activity.ContentResolver.Query(uri, null, null, null, null);
try
{
if (cursor != null && cursor.MoveToFirst())
fileName = cursor.GetString(cursor.GetColumnIndex(OpenableColumns.DisplayName));
}
finally
{
cursor.Close();
}
response.SendChunked = false;
response.ContentType = "audio/mpeg";
response.AddHeader("Content-disposition", "attachment; filename=" + fileName);
byte[] buffer = new byte[64 * 1024];
int read;
using (BinaryWriter bw = new BinaryWriter(response.OutputStream))
{
while ((read = file.Read(buffer, 0, buffer.Length)) > 0)
{
bw.Write(buffer, 0, read);
bw.Flush();
}
bw.Close();
response.ContentLength64 = bw.BaseStream.Length;
}
response.StatusCode = (int)HttpStatusCode.OK;
response.StatusDescription = "OK";
response.OutputStream.Close();
}
I'm not sure how this code is not throwing a "cannot access a closed stream" exception:
bw.Close();
response.ContentLength64 = bw.BaseStream.Length;
But... retrieve the length before closing the stream:
response.ContentLength64 = bw.BaseStream.Length;
bw.Close();

Download .xls file from a url

I'm trying to download an xls file from a url:
http://www.site.com/ff/excel/file.aspx?deven=0
I'm using this code but when the download is complete the file is not properly downloaded. How can I download this file correctly?
string remoteFilename="http://www.site.com/ff/excel/file.aspx?deven=0";
string localFilename = "D:\\1\\1.xls";
Stream remoteStream = null;
Stream localStream = null;
WebResponse response = null;
try
{
// Create a request for the specified remote file name
WebRequest request = WebRequest.Create(remoteFilename);
if (request != null)
{
// Send the request to the server and retrieve the
// WebResponse object
response = request.GetResponse();
response.ContentType = "application/vnd.ms-excel";
if (response != null)
{
// Once the WebResponse object has been retrieved,
// get the stream object associated with the response's data
remoteStream = response.GetResponseStream();
// Create the local file
localStream = File.Create(localFilename);
// Allocate a 1k buffer
byte[] buffer = new byte[1024];
int bytesRead;
// Simple do/while loop to read from stream until
// no bytes are returned
do
{
// Read data (up to 1k) from the stream
bytesRead = remoteStream.Read(buffer, 0, buffer.Length);
// Write the data to the local file
localStream.Write(buffer, 0, bytesRead);
// Increment total bytes processed
} while (bytesRead > 0);
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
// Close the response and streams objects here
// to make sure they're closed even if an exception
// is thrown at some point
if (response != null) response.Close();
if (remoteStream != null) remoteStream.Close();
if (localStream != null) localStream.Close();
}
MessageBox.Show("file downl");
Use WebClient, it's much simpler:
using (WebClient webClient = new WebClient())
{
webClient.DownloadFile(remoteFileName, localFilename);
}
if(File.Exists(localFilename))
MessageBox.Show("File Downloaded");
Try flushing with localStream.Flush() AFTER your do {} while(), you might also want to wrap with a using statement.
For example:
// Create the local file
using (localStream = File.Create(localFilename)) {
// Allocate a 1k buffer
byte[] buffer = new byte[1024];
int bytesRead;
// Simple do/while loop to read from stream until
// no bytes are returned
do {
// Read data (up to 1k) from the stream
bytesRead = remoteStream.Read(buffer, 0, buffer.Length);
// Write the data to the local file
localStream.Write(buffer, 0, bytesRead);
// Increment total bytes processed
} while (bytesRead > 0);
localStream.Flush();
}
This is how I download Excel files using a FilePathResult.
public FilePathResult DownloadFile(int ID)
{
var log = _db.Logs.FirstOrDefault(x => x.LogID == ID);
//Download the spreadsheet
string fileName = string.Format("{0}.xlsx", ID);
string path = _directory + "\\" + fileName;
return File(path, "application/vnd.ms-excel", string.Format("{0}.xlsx", log.ReportTitle));
}

How to download jpg/doc file from my server with Url in asp.net web application

My problem is unable to download file from sever
My code work fine for any Google image-url (eg.:-http://blogs.independent.co.uk/wp-content/uploads/2012/12/google-zip.jpg)
but it is not work in case of my server image-url("eg.:-[http://110.15.445.87/xyz/abc/123.jpg]")
i dont know where is problem
my code is :-
//Create a stream for the file
Stream stream = null;
//This controls how many bytes to read at a time and send to the client
int bytesToRead = 10000;
// Buffer to read bytes in chunk size specified above
byte[] buffer = new Byte[bytesToRead];
// The number of bytes read
try
{
String Url = "http://112.196.32.51/ll1/UploadFiles/13062402231250.jpg";
//String Url = "http://blogs.independent.co.uk/wp-content/uploads/2012/12/google-zip.jpg";
//Create a WebRequest to get the file
HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(Url);
//Create a response for this request
HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();
if (fileReq.ContentLength > 0)
fileResp.ContentLength = fileReq.ContentLength;
//Get the Stream returned from the response
stream = fileResp.GetResponseStream();
// prepare the response to the client. resp is the client Response
var resp = HttpContext.Current.Response;
//Indicate the type of data being sent
resp.ContentType = "application/octet-stream";
String fileName = "Rock.jpg";
//Name the file
resp.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
int length;
do
{
// Verify that the client is connected.
if (resp.IsClientConnected)
{
// Read data into the buffer.
length = stream.Read(buffer, 0, bytesToRead);
// and write it out to the response's output stream
resp.OutputStream.Write(buffer, 0, length);
// Flush the data
resp.Flush();
//Clear the buffer
buffer = new Byte[bytesToRead];
}
else
{
// cancel the download if client has disconnected
length = -1;
}
} while (length > 0); //Repeat until no data is read
}
finally
{
if (stream != null)
{
//Close the input stream
stream.Close();
}
}
}

IIS7 buffer size limit

My problem happens when trying to download a video file via http request
in the following operating systems using IIS7:
win2008 32Bit, Win2008 R2 64Bit
Currently works fine on: win2003 , vista64 (IIS6)
Problem description:
When users request a file larger than 256mb via C# they get a limited file, even when
using Content-Length param it seems that the file get the right size but not the full
content.
When requesting the URL of the file, I get the full file, the problem occurs only via
the C# script, also the C# response that the full buffer was sent to the user.
I've changed the IIS7 settings in the article:
http://blog.twinharbor.com/2011/07/28/fixing-iis7-maximum-upload-size/
and still it doesn't work.
Also, there are no remarks or errors anywhere.
Please find a sample of my code:
var context = System.Web.HttpContext.Current;
context.Response.ContentEncoding = Encoding.GetEncoding("windows-1255");
context.Response.HeaderEncoding = Encoding.GetEncoding("UTF-8");
context.Response.Charset = "utf-8";
System.IO.Stream iStream = null;
// Buffer to read 100K bytes in chunk:
byte[] buffer = new Byte[100000];
// Length of the file:
int length=0;
// Total bytes to read:
long dataToRead=0;
// Identify the file to download including its path.
string filepath = u.Trim(BigFile);
// Identify the file name.
string filename = System.IO.Path.GetFileName(filepath);
Start.Value = u.Time();
try
{
iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
dataToRead = iStream.Length;
context.Response.Charset = "";
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
context.Response.AddHeader("Content-Length", dataToRead.ToString());
while (dataToRead > 0)
{
if (context.Response.IsClientConnected)
{
length = iStream.Read(buffer, 0, 100000);
context.Response.OutputStream.Write(buffer, 0, length);
context.Response.Flush();
buffer = new Byte[100000];
dataToRead = dataToRead - length;
}
else
{
dataToRead = -1;
}
}
}
catch (Exception ex)
{
context.Response.Write("Error : " + ex.Message);
}
finally
{
if (iStream != null)
{
iStream.Close();
}
context.Response.Close();
}
I'll appericiate your help.
Thanks.

Categories