2015-08-28 73 views
0

我有一個名爲Download的鏈接,他需要將它以二進制格式下載到數據庫中記錄的XML文件的瀏覽器中。我究竟做錯了什麼?如何以二進制格式下載xml文件?

遵循下面的代碼:

protected void DownloadFile_Click(object sender, EventArgs e) 
    { 
     int invoiceId = int.Parse((sender as LinkButton).CommandArgument); 

     InvoiceManager iv = new InvoiceManager(); 
     Invoice invoice = iv.Find(invoiceId); 
     if (invoice != null) 
     { 
      byte[] fileInBytes = invoice.FileContent; 

      // Send the XML file to the web browser for download. 
      Response.Clear(); 
      Response.Buffer = true; 
      Response.ContentType = "text/xml"; 
      Response.AppendHeader("Content-Disposition", "attachment; filename=" + invoice.FileName); 
      Response.BinaryWrite(fileInBytes); 
      Response.End(); 

     } 
    } 

回答

0

如果你的意思是它顯示在瀏覽器而不是提示下載,請嘗試更改從文本/ XML你的ContentType到

protected void DownloadFile_Click(object sender, EventArgs e) 
{ 
    int invoiceId = int.Parse((sender as LinkButton).CommandArgument); 

    InvoiceManager iv = new InvoiceManager(); 
    Invoice invoice = iv.Find(invoiceId); 
    if (invoice != null) 
    { 
     byte[] fileInBytes = invoice.FileContent; 

     // Send the XML file to the web browser for download. 
     Response.Clear(); 
     Response.Buffer = true; 
     Response.ContentType = "application/octet-stream"; 
     Response.AppendHeader("Content-Disposition", "attachment; filename=" + invoice.FileName); 
     Response.BinaryWrite(fileInBytes); 
     Response.End(); 

    } 
} 

這樣,你將強制瀏覽器提示文件被下載,而不是嘗試在瀏覽器窗口中顯示它。