I created a site with C# which can download files. after calling
//A webservice returning a stream with the document data.
Stream checkOut = FileProxy.RetrieveDocument(Ticket, ID);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.BufferOutput = true;
HttpContext.Current.Response.ContentType = "application/x-download";
HttpContext.Current.Response.AddHeader("Content-Disposition", "atachment; filename=" + filenamevariable);
HttpContext.Current.Response.CacheControl = "public";
byte[] buffer = new byte[255];
int butesRead = 0;
while ((bytesread = checkOut.Read(buffer, 0, 255)) > 0)
{
if(HttpContext.Current.REsponse.IsClientConnected)
{
HttpContext.Current.Response.OutputStream.Write(buffer, 0, buffer.Length);
HttpContext.Current.Response.Flush();
}
}
Httpcontext.Current.Response.Close();
checkOut.Close();
Running this code succesfully downloads the document but i can not continue using the site (Buttons don't work anymore). Am i forgetting something after the download completion?
Related
I have tried to download and opened a file object stored in Server, but not able to open the file post download. Please find the sample code I am trying as below. I have used Content-Disposition to inline, but still it is not working as mentioned in other solution to this problem. It just downloads, but don't open. Any help please on this?
protected void Page_Load(object sender, EventArgs e)
{
string filePath = this.Server.MapPath("~/Scripts/48A4-4972-AEBE-8E7C11AE64AF");
string fileName = "crma.jpg";
FileStream stream = null;
HttpResponse response = HttpContext.Current.Response;
long dataToRead;
try
{
stream = new FileStream(filePath, FileMode.Open);
dataToRead = stream.Length;
response.ClearContent();
response.AddHeader("Content-Disposition", "inline; filename=" + "\"" + fileName + "\"");
response.AddHeader("Content-Length", dataToRead.ToString());
response.ContentType = "application/jpg";
byte[] buffer = new Byte[10000];
while (dataToRead > 0)
{
if (response.IsClientConnected)
{
int length = stream.Read(buffer, 0, 10000);
response.OutputStream.Write(buffer, 0, length);
response.Flush();
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
dataToRead = -1;
}
}
}
finally
{
if (stream != null)
stream.Close();
response.End();
response.Close();
}
}
I use IHttpHandler to Download a file from Server.Everything works fine.
But it shows the data on browser instead of download it. I need to download the file from the server like we do download from other servers.
Could anyone suggest me, what should I do to download the file,
Or what is the convenient way to download a file(pdf,mp4 etc).
public void ProcessRequest(HttpContext context)
{
string strPathName = "";
if (context.Request.QueryString["fileName"] != null)
{
strPathName = context.Request.QueryString["fileName"].ToString();
}
string filename = context.Server.MapPath("~/MyPath/" + strPathName);
System.IO.Stream oStream = null;
oStream =
new System.IO.FileStream
(path: filename,
mode: System.IO.FileMode.Open,
share: System.IO.FileShare.Read,
access: System.IO.FileAccess.Read);
try
{
context.Response.ClearHeaders();
context.Response.Buffer = false;
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition", "attachment");
long lngFileLength = oStream.Length;
context.Response.AddHeader("Content-Length", lngFileLength.ToString());
long lngDataToRead = lngFileLength;
while (lngDataToRead > 0)
{
if (context.Response.IsClientConnected)
{
int intBufferSize = 8 * 1024;
byte[] bytBuffers =
new System.Byte[intBufferSize];
int intTheBytesThatReallyHasBeenReadFromTheStream =
oStream.Read(buffer: bytBuffers, offset: 0, count: intBufferSize);
context.Response.OutputStream.Write
(buffer: bytBuffers, offset: 0,
count: intTheBytesThatReallyHasBeenReadFromTheStream);
context.Response.Flush();
lngDataToRead =
lngDataToRead - intTheBytesThatReallyHasBeenReadFromTheStream;
}
else
{
lngDataToRead = -1;
}
}
}
catch { }
finally
{
if (oStream != null)
{
oStream.Close();
oStream.Dispose();
oStream = null;
}
context.Response.Close();
}
}
You can't directly download a file via ajax, it only returns the data into a JS variable in the page's code, instead of triggering a traditional request and download.
Your button needs to make a standard HTTP request, not an ajax call.
I have a aspx page in window. Now i want to close it from cs code:
string result = #"<script type='text/javascript'>
window.returnValue = true;
window.close();
</script>";
Response.Write(result);
It's work fine.
Now i want to save a file and then close a window. And my code from above not work. I get a save file dialog, save a fine, but my window not close.
What i should do in this case?
SAVE FILE CODE
File.WriteAllBytes(docFileName, documentStream.ToArray());
fi = new FileInfo(docFileName);
if (fi.Exists)
{
byte[] buffer;
using (FileStream fileStream = new FileStream(docFileName, FileMode.Open))
{
int fileSize = (int)fileStream.Length;
buffer = new byte[fileSize];
// Read file into buffer
fileStream.Read(buffer, 0, fileSize);
fileStream.Close();
fi.Delete();
}
Response.Clear();
Response.Buffer = true;
Response.BufferOutput = true;
Response.ContentType = "application/x-download";
Response.AddHeader("Content-Disposition", "attachment; filename=" + docFileName);
Response.CacheControl = "public";
// writes buffer to OutputStream
Response.OutputStream.Write(buffer, 0, buffer.Length);
Response.End();
You cannot close the window like that.
You can only close the windows that was created by the script.
In my code I want to upload and download a specific JSON-File to a FTP-Server.
The serializing works great and also the upload. When i look up the file via - for example - FileZilla, the content of the file is correct. (on the server)
But when i download this file with my application (and with my code - NOT with FileZilla), I don't get any exceptions, but the file is nearly empty. This is the only content:
{}
And here is my code for downloading:
string ResponseDescription = "";
FtpWebRequest req = (FtpWebRequest)FtpWebRequest.Create("ftp://" + "ftp.strato.com" + "/" + verzeichnis + "/" + file.Name);
req.Method = WebRequestMethods.Ftp.DownloadFile;
req.Credentials = new NetworkCredential(this.benutzer, this.passwort);
req.UseBinary = true;
req.UsePassive = false;
req.Proxy = null;
try
{
FtpWebResponse response = (FtpWebResponse)req.GetResponse();
Stream stream = response.GetResponseStream();
byte[] buffer = new byte[2048];
FileStream fs = new FileStream(destinationFolder + #"/" + destinationFile.Name, FileMode.Create);
int ReadCount = stream.Read(buffer, 0, buffer.Length);
while (ReadCount > 0)
{
fs.Write(buffer, 0, ReadCount);
ReadCount = stream.Read(buffer, 0, buffer.Length);
}
ResponseDescription = response.StatusDescription;
fs.Close();
stream.Close();
return true;
}
catch (Exception e)
{
MessageBox.Show(e.Message); // TODO - better Errorhandling
return false;
}
I found the solution. It was my mistake. The problem wasnt the download - the code was correct (as you said).
After downloading the file the JSON-Deserialization runs and here was the cause. I had a little mistake in my deserialization-logic.
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.