在快速响应中使用特殊字符(变音符号)

时间:2017-11-14 20:42:40

标签: node.js express

我正在使用Express来提供这样的文件下载:

const fileStream = Storage.getFileStream(path);
res.setHeader('Content-disposition', `attachment; filename="${filename}"`);
res.setHeader('Content-type', contentType);
res.setHeader('Content-length', size);
fileStream.pipe(res);

filename包含特殊字符(Ä,Ü,è,...)时,会抛出错误,说我正在使用不允许使用的字符。

我找到了使用unidecode的解决方案。但是有一种解决方案可以保持“Ä”而不是将其转换为“A”

我搜索这个问题,但是我对如何以正确的方式处理这个问题感到很困惑,所以请原谅我这个问题是否重复...

解决方案(稍后补充):我发现这个解决方案对我有用,并且在文件名中保留所有特殊字符:

const filename = encodeURI(file.filename);
res.setHeader('Content-disposition', `attachment; filename*=UTF-8''${filename}; filename=${filename}`);
res.setHeader('Content-type', contentType);
res.setHeader('Content-length', size);

1 个答案:

答案 0 :(得分:0)

您可以尝试使用其中一个优秀的库来规范化字符串 JavaScript Unicode 8.0规范化 - NFC,NFD,NFKC,NFKD。 哪个可以使用: -

npm install unorm

示例代码 -

var unorm = require('unorm');

var text =
  'The \u212B symbol invented by A. J. \u00C5ngstr\u00F6m ' +
  '(1814, L\u00F6gd\u00F6, \u2013 1874) denotes the length ' +
  '10\u207B\u00B9\u2070 m.';

var combining = /[\u0300-\u036F]/g; // Use XRegExp('\\p{M}', 'g'); see 
example.js.

console.log('Regular:  ' + text);
console.log('NFC:      ' + unorm.nfc(text));
console.log('NFD:      ' + unorm.nfd(text));
console.log('NFKC:     ' + unorm.nfkc(text));
console.log('NFKD: *   ' + unorm.nfkd(text).replace(combining, ''));
console.log(' * = Combining characters removed from decomposed form.');

来源:https://github.com/walling/unorm 我希望它有效。

相关问题