Запись текста UTF8 в файл - PullRequest
4 голосов
/ 15 мая 2010

Я использую следующую функцию для сохранения текста в файл (в IE-8 с ActiveX).

function saveFile(strFullPath, strContent)
{
    var fso = new ActiveXObject( "Scripting.FileSystemObject" );

    var flOutput = fso.CreateTextFile( strFullPath, true ); //true for overwrite
    flOutput.Write( strContent );
    flOutput.Close();
}

Код работает нормально, если текст полностью латинский-9, но когда текст содержит хотя бы один символ в кодировке UTF-8, запись не удалась.

ActiveX FileSystemObject не поддерживает UTF-8, кажется. Сначала я попробовал кодировать текст UTF-16, но результат был искажен. Что такое обходной путь?

Ответы [ 4 ]

5 голосов
/ 15 мая 2010

Попробуйте это:

function saveFile(strFullPath, strContent) {
 var fso = new ActiveXObject("Scripting.FileSystemObject");
 var utf8Enc = new ActiveXObject("Utf8Lib.Utf8Enc");
 var flOutput = fso.CreateTextFile(strFullPath, true); //true for overwrite
 flOutput.BinaryWrite(utf8Enc.UnicodeToUtf8(strContent));
 flOutput.Close();
}
2 голосов
/ 15 мая 2010

Добавьте третий параметр, true, при вызове метода CreateTextFile. см. Эту страницу .

1 голос
/ 15 мая 2010

У метода CreateTextFile есть третий параметр, который определяет, будет ли файл записан в юникоде или нет. Вы можете сделать как:

var flOutput = fso.CreateTextFile(strFullPath,true, true);

Интересно, что в далеком прошлом я создал этот маленький скрипт для сохранения файлов в формате Unicode:

Set FSO=CreateObject("Scripting.FileSystemObject")
Value = InputBox ("Enter the path of the file you want to save in Unicode format.")

If Len(Trim(Value)) > 0 Then
    If FSO.FileExists(Value) Then
        Set iFile = FSO.OpenTextFile (Value)
        Data = iFile.ReadAll
        iFile.Close

        Set oFile = FSO.CreateTextFile (FSO.GetParentFolderName(Value) & "\Unicode" & GetExtention(Value),True,True)
        oFile.Write Data
        oFile.Close

        If FSO.FileExists (FSO.GetParentFolderName(Value) & "\Unicode" & GetExtention(Value)) Then
            MsgBox "File successfully saved to:" & vbCrLf & vbCrLf &  FSO.GetParentFolderName(Value) & "\Unicode" & GetExtention(Value),vbInformation
        Else
            MsgBox "Unknown error was encountered!",vbCritical
        End If
    Else
        MsgBox "Make sure that you have entered the correct file path.",vbExclamation
    End If
End If

Set iFile = Nothing
Set oFile= Nothing
Set FSO= Nothing

Function GetExtention (Path)
    GetExtention = Right(Path,4)
End Function

Примечание: Это код VBScript, вы должны сохранить этот код в файле, подобном unicode.vbs, и как только вы дважды щелкните по этому файлу, он запустится.

0 голосов
/ 15 сентября 2014
function saveFile(strFullPath, strContent) {
    var fso = new ActiveXObject( "Scripting.FileSystemObject" );
    var flOutput = fso.CreateTextFile( strFullPath, true, true ); //true for overwrite // true for unicode
    flOutput.Write( strContent );
    flOutput.Close();
}

object.CreateTextFile(filename[, overwrite[, unicode]])

...