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.
Related
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.
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.
can anyone please explain this code
if (e.CommandName == "download")
{
string filename = e.CommandArgument.ToString();
string path = MapPath("~/Docfiles/" + filename);
byte[] bts = System.IO.File.ReadAllBytes(path);
Response.Clear();
Response.ClearHeaders();
Response.AddHeader("Content-Type", "Application/octet-stream");
Response.AddHeader("Content-Length", bts.Length.ToString());
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
Response.BinaryWrite(bts);
Response.Flush();
Response.End();
}
what is command argument, mappath, and also what is this
"Content-Type", "Application/octet-stream"
and also
Response.AddHeader("Content-Length", bts.Length.ToString());
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
Response.BinaryWrite(bts);
Response.Flush();
First, I advise you to use the MSDN documentation to search for more information about the objects and methods you wanna know more about. MSDN is a useful network and should be used.
Quoting the MSDN CommandArgument : "Gets or sets an optional parameter passed to the Command event along with the associated CommandName". It is used to get an parameter that was passed to the command event. In this case, it was the file name.
string filename = e.CommandArgument.ToString();
The MapPath is used to map a specified path to a physical path. Using this you get the real path of the file. For example: "C:\Docfiles\Yourfile.pdf"
string path = MapPath("~/Docfiles/" + filename);
The ReadAllBytes method, opens a file, reads the content and then closes the file. This return the content of this file as a byte array.
byte[] bts = System.IO.File.ReadAllBytes(path);
The Response object is used to send output to the user from the server.
Response.Clear();
Response.ClearHeaders();
Response.AddHeader is used to build the header of response that will be sent back to user. We use it to set infos about the data we are sending back to the client.
The "Content-Type" attribute is used to especify what kind of file you are returning to the user.
Response.AddHeader("Content-Type", "Application/octet-stream");
The "Content-Length" attribute is used to inform to the browser the size of the the file you are returning.
Response.AddHeader("Content-Length", bts.Length.ToString());
The "Content-Disposition" is used to inform the name of the file that will be returned. For example "file1.doc"
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
The "BinaryWrite()" write your file (who, at this moment, is in a byte array format) to the current HTTP output without any character conversion.
Response.BinaryWrite(bts);
The Flush method sends buffered output immediately.
Response.Flush();
And, finally, causes the server to stop processing the request and return the current result.
Response.End();
If the command is download, most likely from a grid button, then get the name of the file as the argument (these are properties on a button control), and send it to the browser. This prompts the user to download the file.
I want to download the files from server. When downloading i want to change the file name.
But I can't change the file name totally when the filename contains spaces.
My Code is as Below
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
This lets the user save the file to their computer.
But when i save the file, only the first word of the filename is saved.
eg. I want to give the file name as ("CCNA Q&A.pdf") but the file save as ("CCNA")
I want to know how to save the filename with spaces.
in firefox: Server.UrlEncode() will replace space with %20
just put the filename between double quotes filename = "\"" + filename + "\"";
Have you tried Server.UrlEncode()?
Or you can omit all non alphabetic characters (' ', -, etc) whith _-s (regular expression replace).
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
I was having the same problem as I was trying to download a text file having spaces in its name. I have solved this using UrlDecode function. As browser converts spaces to '+' symbol, using decode function one need to convert these '+' to spaces.
fileName = Server.UrlDecode(fileName);
Response.AddHeader("content-disposition", "attachment; filename=\"" + fileName + "\"");
You'll have to wrap it in additional quotes:
Response.AddHeader("content-disposition", "attachment; filename=\"" + fileName + "\"");
I am exporting a excel file from "c:Test\data.xls" using the responce object
like:
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
it is opening a dialog box.But Now we don't need the dialog box.we want to directly open file without dialog.
Can any body help me out
use
response.AddHeader("Content-Disposition", "inline; filename=" + FileName + ";");
Whether it opens directly depends on client-side security settings to this might work but there is no guarantee...
Instead of attaching file to response you nee write it's content to response stream.
//Set the appropriate ContentType.
Response.ContentType = "application/vnd.ms-excel"; // not sure in content type
//Get the physical path to the file.
string filePath = #"c:Test\data.xls";
//Write the file directly to the HTTP content output stream.
Response.WriteFile(filePath);
Response.End();
But also it depeneds on the client side settings.