修复报销附件上传与中文文件名(07-28-travel-reimbursement-guide)
这个提交包含在:
@@ -0,0 +1,67 @@
|
||||
const DEFAULT_FILE_NAME = "attachment.bin";
|
||||
const DEFAULT_MAX_FILE_NAME_CODE_POINTS = 180;
|
||||
const ALLOWED_DISPOSITIONS = new Set(["attachment", "inline"]);
|
||||
|
||||
function truncateCodePoints(value, maxCodePoints) {
|
||||
const codePoints = Array.from(value);
|
||||
return codePoints.length <= maxCodePoints
|
||||
? value
|
||||
: codePoints.slice(0, maxCodePoints).join("");
|
||||
}
|
||||
|
||||
function sanitizeHeaderFileName(fileName, { maxCodePoints = DEFAULT_MAX_FILE_NAME_CODE_POINTS } = {}) {
|
||||
const source = typeof fileName === "string" && fileName.trim()
|
||||
? fileName.normalize("NFC").trim()
|
||||
: DEFAULT_FILE_NAME;
|
||||
const sanitized = truncateCodePoints(
|
||||
source
|
||||
.replace(/[\\/]/gu, "_")
|
||||
.replace(/[\u0000-\u001f\u007f-\u009f]/gu, "_")
|
||||
.replace(/[\u200b-\u200f\u202a-\u202e\u2060-\u2069\ufeff]/gu, "_")
|
||||
.replace(/"+/gu, "_")
|
||||
.replace(/\s+/gu, " ")
|
||||
.trim(),
|
||||
maxCodePoints,
|
||||
);
|
||||
return sanitized && sanitized !== "." && sanitized !== ".."
|
||||
? sanitized
|
||||
: DEFAULT_FILE_NAME;
|
||||
}
|
||||
|
||||
function buildAsciiFallback(fileName) {
|
||||
const lastDotIndex = fileName.lastIndexOf(".");
|
||||
const rawExtension = lastDotIndex > 0 ? fileName.slice(lastDotIndex).toLowerCase() : ".bin";
|
||||
const extension = /^\.[a-z0-9]{1,10}$/u.test(rawExtension) ? rawExtension : ".bin";
|
||||
const rawStem = lastDotIndex > 0 ? fileName.slice(0, lastDotIndex) : fileName;
|
||||
const asciiStem = rawStem
|
||||
.normalize("NFKD")
|
||||
.replace(/[\u0300-\u036f]/gu, "")
|
||||
.replace(/[^a-zA-Z0-9._-]+/gu, "_")
|
||||
.replace(/_+/gu, "_")
|
||||
.replace(/^[._-]+|[._-]+$/gu, "")
|
||||
.slice(0, 100);
|
||||
return `${asciiStem || "attachment"}${extension}`;
|
||||
}
|
||||
|
||||
function encodeRfc5987Value(value) {
|
||||
return encodeURIComponent(value).replace(/[\u0027\u0028\u0029\u002a]/gu, (character) =>
|
||||
`%${character.charCodeAt(0).toString(16).toUpperCase()}`,
|
||||
);
|
||||
}
|
||||
|
||||
function buildAttachmentContentDisposition(
|
||||
fileName,
|
||||
{ disposition = "attachment", maxCodePoints = DEFAULT_MAX_FILE_NAME_CODE_POINTS } = {},
|
||||
) {
|
||||
if (!ALLOWED_DISPOSITIONS.has(disposition)) {
|
||||
throw new TypeError("disposition must be attachment or inline");
|
||||
}
|
||||
const safeFileName = sanitizeHeaderFileName(fileName, { maxCodePoints });
|
||||
const asciiFallback = buildAsciiFallback(safeFileName);
|
||||
return `${disposition}; filename="${asciiFallback}"; filename*=UTF-8''${encodeRfc5987Value(safeFileName)}`;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_MAX_FILE_NAME_CODE_POINTS,
|
||||
buildAttachmentContentDisposition,
|
||||
};
|
||||
在新工单中引用
屏蔽一个用户