ASP UTF-8编码生成静态网页的函数

  以下函数采用FSO对象,文件位置在FSO.ASP。FSO对象的文件编码属性只有三种,系统默认,Unicode,ASCII,并没有我们要的utf-8,所以一般中文系统上使用FSO对象生成的文件都是gb2312网页编码格式,无法生成UTF-8编码,因此,英文等拉丁语系和中文可以正常显示,但象俄语等非拉丁语系,页面就会出现乱码。

  

复制代码 代码如下:

  function createfile(sfilename,scontent)

  set fso=server.CreateObject("scripting.filesystemobject")

  'set f1=fso.opentextfile(sfilename,2,true,-1) 'append=8 only write=2 Unicode编码=-1

  set f1=fso.opentextfile(sfilename,2,true)

  f1.write(scontent)

  f1.close

  set fso=nothing

  end function

  选择用ADODB.STREAM对象来替代FSO对象,因为STREAM类有LOADFROMFILE和SAVETOFILE方法,并且有一个至关重要的属性CHARSET,这是FSO没有的。以下函数采用用Adodb.Stream编写,成功生成UTF-8网页文件。

  

复制代码 代码如下:

  function createfile(sfilename,scontent)

  Set objStream = Server.CreateObject("ADODB.Stream")

  With objStream

  .Open

  .Charset = "utf-8"

  .Position = objStream.Size

  .WriteText=scontent

  .SaveToFile sfilename,2

  .Close

  End With

  Set objStream = Nothing

  end function

  对于采用FSO的程序,只要把这个函数修改一下, 函数名称不变,就可以正常运行, 比较省事方便。

  如果采用模板生成文件, 还需要把模板文件用UTF-8编码读进来,否则,后台发布正确文件编码,但模板文件读进来是用FSO的GB2312编码,模板页面的俄语等非拉丁语系,就会出现乱码。函数修改如下:

  原来采用的FSO 的READFILE函数

  

复制代码 代码如下:

  function readfile(sfilename)

  Set fso=server.CreateObject("scripting.filesystemobject")

  Set f = fso.OpenTextFile(sfilename, 1, true)

  if not f.AtEndOfStream then readfile = f.readAll

  Set f=nothing

  Set fso=nothing

  end function

  替换采用的ADODB.STREAM 的READFILE函数

  注意根据实际需要,去掉或保留Function readfile (sfilename,charset)charset参数charset。

  

复制代码 代码如下:

  Function readfile (sfilename)

  Dim f

  Set stm=server.CreateObject("adodb.stream")

  stm.Type=2 '以本模式读取

  stm.mode=3

  stm.charset="utf-8"

  stm.open

  stm.loadfromfile sfilename

  f=stm.readtext

  stm.Close

  Set stm=Nothing

  readfile=f

  End Function

  关于文件编码和网页编码, 请参考“字符集Charset和文件编码Encoding的区别详解”。

  其他样例程序

  

复制代码 代码如下:

  '-------------------------------------------------

  '函数名称:ReadTextFile

  '作用:利用AdoDb.Stream对象来读取UTF-8格式的文本文件

  '----------------------------------------------------

  Function ReadFromTextFile (FileUrl,CharSet)

  Dim str

  Set stm=server.CreateObject("adodb.stream")

  stm.Type=2 '以本模式读取

  stm.mode=3

  stm.charset=CharSet

  stm.open

  stm.loadfromfile server.MapPath(FileUrl)

  str=stm.readtext

  stm.Close

  Set stm=nothing

  ReadFromTextFile=str

  End Function

  '-------------------------------------------------

  '函数名称:WriteToTextFile

  '作用:利用AdoDb.Stream对象来写入UTF-8格式的文本文件

  '----------------------------------------------------

  Sub WriteToTextFile (FileUrl,byval Str,CharSet)

  Set stm=Server.CreateObject("adodb.stream")

  stm.Type=2 '以本模式读取

  stm.mode=3

  stm.charset=CharSet

  stm.open

  stm.WriteText str

  stm.SaveToFile server.MapPath(FileUrl),2

  stm.flush

  stm.Close

  Set stm=Nothing

  End Sub

  其中, 这一行要注意路径问题,stm.SaveToFile server.MapPath(FileUrl),2