UTF-8 text file generated from ASP

In the previous post, I've described how to output plain text encoded as UTF-8 from an ASP script. To save that text to a file on the client's disk drive, you can add the Content-disposition header, indicating the ASP script response is actually an attachment that has to be saved to disk. However, some Windows programs expect to see the Byte-order mark in front of the UTF-8 text. To generate this byte stream, I've used a simple trick: first I've switched the codepage to US-ASCII (ensuring there will be no character transcoding), wrote the three byte sequence and switched back to UTF-8 to write the rest of the text.
Sub OutputCSV(finalText)
  Response.Clear
  Response.Charset = "utf-8"
  Response.ContentType = "text/plain"
  Response.AddHeader "Content-disposition", "attachment; filename=savedData.csv"
  Response.Expires = 0
  Response.Codepage = 1252
  Response.Write Chr(239) & Chr(187) & Chr(191)
  Response.Codepage = 65001
  Response.Write finalText
  Response.End
End Sub

No comments:

Post a Comment