node-formidable slugify filename

时间:2014-06-14 15:09:18

标签: node.js formidable

我坚持使用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!")
                    }
                });
    }     
});

1 个答案:

答案 0 :(得分:0)

您没有为“子弹”功能提供代码,因此我提供了新的子弹功能。 您的代码中也未给出“ 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
}