Skip to content
This repository has been archived by the owner on Jan 10, 2025. It is now read-only.

Commit

Permalink
fix: 🐛 修复curl post文件时中文文件名的问题
Browse files Browse the repository at this point in the history
Closes: #71
  • Loading branch information
danni-cool committed Dec 5, 2023
1 parent 06e6400 commit 85c1407
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/route/msg.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ module.exports = function registerPushHook({ app, bot }) {
to = req.body.to
isRoom = req.body.isRoom || '0'
content = req.files.find((item) => item.fieldname === 'content') || {}
// 转化上传文件名中文字符但是被编码成 iso885910 的问题
content.originalname &&
(content.originalname = Utils.tryConvertCnCharToUtf8Char(
content.originalname,
))
type = 'file'

// 校验必填参数
Expand Down
24 changes: 24 additions & 0 deletions src/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,29 @@ const parseJsonLikeStr = (jsonLikeStr) => {
return JSON.parse(formatStr)
}

// 检测每个字符是否都可以被iso-8859-1表示,因为curl http1.1 在发送form-data时,文件名是中文的话会被编码成 iso-8859-1表示
// https://github.com/danni-cool/docker-wechatbot-webhook/issues/71
function tryConvertCnCharToUtf8Char(str) {
const isIso88591 = [...str].every((char) => {
const codePoint = char.charCodeAt(0)
return codePoint >= 0x00 && codePoint <= 0xff
})

if (isIso88591) {
// 假设原始编码是 ISO-8859-1,将每个字符转换为相应的字节
const bytes = new Uint8Array(str.length)
for (let i = 0; i < str.length; i++) {
bytes[i] = str.charCodeAt(i)
}

// 使用 TextDecoder 将 ISO-8859-1 编码的字节解码为 UTF-8 字符串
const decoder = new TextDecoder('UTF-8')
return decoder.decode(bytes)
}

return str
}

module.exports = {
getFileNameFromUrl,
getMediaFromUrl,
Expand All @@ -143,4 +166,5 @@ module.exports = {
generateToken,
equalTrueType,
parseJsonLikeStr,
tryConvertCnCharToUtf8Char,
}

0 comments on commit 85c1407

Please sign in to comment.