fix: Fix the issue of garbled characters when opening UTF-8 encoded files (#9454)

refs: #9411
This commit is contained in:
2025-07-08 14:09:54 +08:00 committed by GitHub
parent 4a07603a7c
commit a067a97e21
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -18,6 +18,7 @@ import (
"strconv" "strconv"
"strings" "strings"
"time" "time"
"unicode/utf8"
"github.com/1Panel-dev/1Panel/agent/app/repo" "github.com/1Panel-dev/1Panel/agent/app/repo"
@ -334,22 +335,24 @@ func (f *FileService) GetContent(op request.FileContentReq) (response.FileInfo,
if len(content) > 1024 { if len(content) > 1024 {
content = content[:1024] content = content[:1024]
} }
_, decodeName, _ := charset.DetermineEncoding(content, "") if !utf8.Valid(content) {
decoder := files.GetDecoderByName(decodeName) _, decodeName, _ := charset.DetermineEncoding(content, "")
if decoder != nil { decoder := files.GetDecoderByName(decodeName)
reader := strings.NewReader(info.Content) if decoder != nil {
var dec *encoding.Decoder reader := strings.NewReader(info.Content)
if decodeName == "windows-1252" { var dec *encoding.Decoder
dec = simplifiedchinese.GBK.NewDecoder() if decodeName == "windows-1252" {
} else { dec = simplifiedchinese.GBK.NewDecoder()
dec = decoder.NewDecoder() } else {
dec = decoder.NewDecoder()
}
decodedReader := transform.NewReader(reader, dec)
contents, err := io.ReadAll(decodedReader)
if err != nil {
return response.FileInfo{}, err
}
info.Content = string(contents)
} }
decodedReader := transform.NewReader(reader, dec)
contents, err := io.ReadAll(decodedReader)
if err != nil {
return response.FileInfo{}, err
}
info.Content = string(contents)
} }
return response.FileInfo{FileInfo: *info}, nil return response.FileInfo{FileInfo: *info}, nil
} }