欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-14 10:43:04
以下函数采用fso对象,文件位置在fso.asp。fso对象的文件编码属性只有三种,系统默认,unicode,ascii,并没有我们要的utf-8,所以一般中文系统上使用f...
以下函数采用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