从字节返回文件下载[] [英] Return file download from byte[]
问题描述
这code
字符串XML = XmlHelper.ToXml(queryTemplate);字节[] = xmlb StringHelper.GetBytes(XML);VAR CD =新System.Net.Mime.ContentDisposition
{
//例如foo.bak
文件名=的String.Format({0} _V {1}的.xml,queryModel.Name,queryModel.Version) //总是提示用户下载,如果你想设置为true
//浏览器试图显示文件内嵌
内嵌=假,
};
Response.AppendHeader(内容处置,cd.ToString());
返回文件(xmlb,应用程序/ XML);
原来的字符串编码不正确,它转换成字节后[]
所以,我需要立即把字符串转换成文件,这样
的FileStream xfile =新的FileStream(Path.Combine(dldir,文件名),FileMode.Create,System.IO.FileAccess.Write);
hssfwb.Write(xfile);
但我并不想这样做,我并不需要的文件下载后。我只是需要将其返回到浏览器的文件下载,不希望有后处理文件删除它可以成为pretty忙碌的时候有很多的要求。
如何纠正从字符串的字符编码为byte []并将其正确返回到浏览器?
该getBytes函数看起来像这样
公共静态的byte [] GetBytes会(字符串str)
{
字节[]字节=新的字节[str.Length *的sizeof(字符)];
System.Buffer.BlockCopy(str.ToCharArray(),0,字节,0,bytes.Length);
返回字节;
}
我有这个答案,原来的问题是字符编码。
解决方案链接低于
<一个href=\"http://stackoverflow.com/questions/14181866/converting-string-to-byte-creates-zero-character\">Converting字符串为byte []创建零字符
This code
string xml = XmlHelper.ToXml(queryTemplate);
byte[] xmlb = StringHelper.GetBytes(xml);
var cd = new System.Net.Mime.ContentDisposition
{
// for example foo.bak
FileName = String.Format("{0}_v{1}.xml", queryModel.Name, queryModel.Version),
// always prompt the user for downloading, set to true if you want
// the browser to try to show the file inline
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(xmlb, "application/xml");
Turns out the string encoding is incorrect after it's converted into byte[]
So I need to put the string immediately into file, like this
FileStream xfile = new FileStream(Path.Combine(dldir, filename), FileMode.Create, System.IO.FileAccess.Write);
hssfwb.Write(xfile);
But I don't want to do this, I don't need the file after the download. I just need to return it to browser as file download and don't want to have to deal with file deletion afterward which can become pretty hectic when there's a lot of request.
How to correct the character encoding from string to byte[] and correctly return it to browser?
The GetBytes function looks like this
public static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
I have had the answer for this, it turns out the problem was character encoding.
The solution link is below
Converting string to byte[] creates zero character
这篇关于从字节返回文件下载[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!