Return file download from byte[]

前端 未结 3 1818
灰色年华
灰色年华 2021-01-21 05:20

This code

string xml = XmlHelper.ToXml(queryTemplate);

byte[] xmlb = StringHelper.GetBytes(xml);

var cd = new System.Net.Mime.ContentDisposition
{
    // for e         


        
相关标签:
3条回答
  • 2021-01-21 05:33

    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

    0 讨论(0)
  • 2021-01-21 05:39

    Something like this would work:

    try
    {
        Response.ContentType = "application/octet-stream"; 
        Response.AddHeader( "Content-Disposition", "attachment; filename=" + filename ); 
        Response.OutputStream.Write(xmlb, 0, xmlb.Length); 
        Response.Flush(); 
    } 
    catch(Exception ex) 
    {
        // An error occurred.. 
    }
    
    0 讨论(0)
  • 2021-01-21 05:44

    In this case:

    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;
    }
    

    You will end up with UTF-16LE encoding, because that's what a char array is internally.

    You should get rid of that function because it's both misleading and redundant duplication of functionality already existing out of the box because System.Text.Encoding.Unicode.GetBytes already does the same thing: An encoding for the UTF-16 format using the little endian byte order.

    If creating a temporary file without specifying encoding works, then you probably want Windows-1252 because that was most likely being used implicitly when creating the file:

    Encoding enc = Encoding.GetEncoding(1252);
    byte[] xmlb = enc.GetBytes(xml);
    

    If you wanted UTF-8 you would do:

    byte[] xmlb = Encoding.UTF8.GetBytes(xml);
    
    0 讨论(0)
提交回复
热议问题