我一直在使用node-formidable对文件名做冗长的处理。我尝试过form.on,但它已经返回了不受欢迎的�替换字符。所以文件名'ěščř.png‘变成了'����.png’而不是escr.png
form.on('end', function(fields, files) {
var new_location = 's:/localhost/nodejs/';
for(var i = 0; i < this.openedFiles.length; i++){
var temp_path = this.openedFiles[i].path;
var file_name = slug(this.openedFiles[i].name);
fs.copy(temp_path, new_location + file_name, function(err) {
if (err) {
console.error(err);}
else {
console.log("success!")
}
});
}
});发布于 2018-12-13 23:15:09
您没有为“slug”函数提供代码,所以我提供了新的slugify函数。'openedFiles‘也没有在你的代码中给出,我假设所有其他的东西都没问题。
在你核心需求的顶端
const path = require('path');使用此代码
form.on('end', function(fields, files) {
var new_location = 's:/localhost/nodejs/';
for(var i = 0; i < this.openedFiles.length; i++){
var temp_path = this.openedFiles[i].path;
var baseName = path.basename(this.openedFiles[i].name);
var extName = path.extname(this.openedFiles[i].name);
var file_name = slugify(baseName) + '.' + extName;
fs.copy(temp_path, new_location + file_name, function(err) {
if (err) {
console.error(err);}
else {
console.log("success!")
}
});
}
});
function slugify(text){
return text.toString().toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text
}https://stackoverflow.com/questions/24221280
复制相似问题