Download file code not working for firefox and IE - asp.net

I have created a code for downloading images. It works fine if the file name has no special characters or the punctuation marks. But I found an issue when the file name contains other language's character or ',' in the file name.
My code is :
private void AddFile(SPFile file)
{
try
{
System.IO.FileInfo fileInfo = new FileInfo(file.Name);
string filename = GeneralMethods.MakeValidFileName(file.Name);
filename += fileInfo.Extension;
byte[] obj = (byte[])file.OpenBinary();
Response.ClearContent();
Response.ClearHeaders();
Response.AppendHeader("Content-Disposition", "attachment; filename= " + filename);
Response.ContentType = "application/octet-stream";
if (Response.IsClientConnected)
Response.BinaryWrite(obj);
Response.Flush();
Response.Close();
}
catch (Exception ex)
{
}
finally
{
}
}
To avoid the other language's characters and other punctuation marks in the file name I created one method to replace non English character to blank.
public static string MakeValidFileName(string name)
{
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
return rgx.Replace(name, "");
}
In my scenario, I have two files 'xäbace 11,5 hm' & 'Png file'. I am able to download these files in Chrome but not able to download in IE & Firefox. And one more thing, the file is downloaded in Firefox but without extension. i.e. the file gets downloaded and after completing if I add extension to that file it works fine.
What should I do to tackle the issue?

Sincerely, I don't understand ASP.
But it seems you are permitting spaces in file names. You should avoid it, because some browsers will force URL encode of the filename, replacing spaces by %20 and messing up with the file path.
Also, in some languages (PHP) spaces in file names can in some cases, force the MIME type to text/html.
For many reasons you should the, avoid spaces in files to be downloaded or just used in the web.

Related

Why i can not find file on the server for download in asp.net?

I'm beginner in asp.net and want to write simple web application to end user can download any file,write this code for that purpose:
string filePath = "~/beh/" + query[0].OstFileName;
FileInfo file = new FileInfo(filePath);
if (file.Exists) {
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + query[0].OstFileName.Trim());
Response.TransmitFile(Server.MapPath("~/beh/" + query[0].OstFileName.Trim()));
Response.End();
} else {
Response.Write("<script>alert('File Not Found 1')</script>");
}
but when run that code i get else block alert,means get File Not Found 1 message,Where is my fault?thanks all.
string filePath = "~/beh/" + query[0].OstFileName;
In this line you specify the path to search for, including the filename.
The next line you check if this file exists and if so save the file from the query result.
However if you check if the file exists before you actually save the file it will never exist.
Change the path to read: string filePath = Server.MapPath("~\beh").
Then add the filename to that once you save the file.
Hope this makes sense.
Your issue is in the following lines.
string filePath = "~/beh/" + query[0].OstFileName;
FileInfo file = new FileInfo(filePath);
You're giving the FileInfo class a virtual path which the FileInfo cannot map to a local physical path on its own. You are however correctly mapping the virtual path to the local file path when you call Response.TransmitFile.
Change your code to the following:
string filePath = "~/beh/" + query[0].OstFileName;
FileInfo file - new FileInfo(Server.MapPath(filePath));
See: https://msdn.microsoft.com/en-us/library/ms524632(v=vs.90).aspx

HttpResponse downloading zip file cuts zip file name

I am using Webforms and I am providing a possibility to download files. However their names have white spaces and commas. What is the way to ensure that all file name will be there? eg if I have a name like:
1991-02-21 1111, ABCD, restofmyfilename.zip
all I get while dowloading is
1991-02-21
code part:
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "attachment;filename=" + response.FileName);
Response.BinaryWrite(response.Bytes);
Response.End();
Did you try wrapping the file name in quotes? For Example:
Response.AddHeader("content-disposition", "attachment;filename=\"" + response.FileName + "\"");
You can slightly modify the FileName to avoid white spaces:
string fileName = response.FileName.Replace(' ','_');
then use this as a filename in your code.

Open pdf in browser with different names

My program generates PDF in Browser (open the PDF in the browser). But when I want save the file in computer, the default name of PDF is always the same (the name of my class).
I want to pass the name for different pdf's... This is my code:
protected void displayPDF(string filePath, string filename)
{
Response.Clear();
Response.ContentType = "Application/PDF";
//what i do with filename?
Response.WriteFile(filePath);
Response.Flush();
Response.End();
}
I tried this:
Response.AddHeader("Content-Disposition", "attachment; filename=myfile.pdf");
But this way, pdf doesn't open in browser, pass like an attachment.
Can you help me?
Thanks.
Try HttpResponse.TransmitFile(path) eg.
http://bojanskr.blogspot.ca/2012/03/providing-file-for-download-trough-save.html?m=1

Save string to client with Open/Save dialog

I am using the following code to write the contents of a string (converted to a byte array) to the client in ASP.NET/C#
byte[] data = StrToByteArray(strData);
Response.ClearContent();
Response.AppendHeader("content-length", data.Length.ToString());
Response.ContentType = "text/plain";
Response.AppendHeader("content-Disposition", "attachment;filename=" + fileName);
Response.BinaryWrite(data);
Response.Flush();
fileName is the name of the file ending with the file extension (.pgn). However, the file is saved as a .txt file, ignoring the extension that I am giving it. Would this have to do with the Response.Contenttype = "text/plain"? How can I get the Open/Save dialog to display and save the correct (.pgn) filename?
Also, if filename is a string separated by dashes or spaces, when the Open/Save dialog comes up, the filename is not displayed in its entirety but it is truncated where the first dash (-) or space (or comma) is encountered. How can this be remedied?
Yes, it is saving .txt because of your Content Type (MIME type). Use image/png.
How about you remove the dashes and spaces? String.Replace is great. fileName.Replace("-", ""); etc.

asp.net ashx handler prompting download instead of displaying file

I implemented a generic handler in my application which works great for images, but when I manually type the handler URL in the browser with the image's querystring it prompts download instead of displaying. Here is my code:
public void ProcessRequest(HttpContext context)
{
if (this.FileName != null)
{
string path = Path.Combine(ConfigurationManager.UploadsDirectory, this.FileName);
if (File.Exists(path) == true)
{
FileStream file = new FileStream(path, FileMode.Open);
byte[] buffer = new byte[(int)file.Length];
file.Read(buffer, 0, (int)file.Length);
file.Close();
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("content-disposition", "attachment; filename=\"" + this.FileName + "\"");
context.Response.BinaryWrite(buffer);
context.Response.End();
}
}
}
I am using the octet-stream because I'm dealing with more than just images and I don't always know the content type of the file. Thanks in advance!
The only way is to specify correct ContentType so the browser know what to do with receiving file, depending on installed plugins (for example, view pdf files in browser frame) and system assosiations (for example, offer to open document in MS Office instead of simple download)
You can try to specify Content Type depending on file extension, i.e.:
if(Path.GetExtension(path) == ".jpg")
context.Response.ContentType = "image/jpeg";
else
context.Response.ContentType = "application/octet-stream";
If you store the ContentType as part of the files metadata, when you pull it back down your could use it.
theFile = GetFile(id)
context.Response.ContentType = theFile.Type;
The content-disposition header is the one that causes your browser to show the download dialog. Remove that line and it will show in the browser.

Resources