【问题标题】:Adding files to same folder with nodeJS使用nodeJS将文件添加到同一文件夹
【发布时间】:2018-08-09 20:03:09
【问题描述】:

我想将mp3, lrc, wav, txt 添加到服务器,文件夹名称将是title,并且上面提到的所有扩展都将具有指定的名称。如代码所示,mp3 为"vocal.mp3"

addSong(event) {

    jQuery('#addItemSave').text("Please wait!");

    this._service.addSong(this.authorText, this.titleText, this.durationText, this.genre).subscribe(
        res => {
            this.data.push(res.data[0]);
            this.addSongFilesToServer();
    });
}

private addSongFilesToServer() {
    this._service.addSongFilesToServer(this.titleText,
            this.mp3file, this.lrcfile, this.pitchfile, this.thumbfile).subscribe(
        res => {
            console.log("Done! Now hide loading icon or what ever...");
            jQuery('#addItemSave').text("Save");
            jQuery('#addNewSongDialog').modal('hide');
            jQuery('#addNewSongDialog').find("input,textarea,select")
                    .val('')
                    .end()
                .find("input[type=checkbox], input[type=radio]")
                    .prop("checked", "")
                    .end();
    });
}

addSongFilesToServer(title, mp3, lrc, txt, thumb) {
    let url = this._config.ServerWithApiUrl + "uploadFiles";
    let body : FormData = new FormData();
    body.append('mp3', mp3, "vocal.mp3");
    body.append('txt', txt, "pitches.txt");
    body.append('lrc', lrc, "lyric.lrc");
    body.append('thumb', thumb, "thumbnail.png");
    body.append('title', title);
    this._config.headers.delete('Content-Type');

    return this._http.post(url, body, { headers: this._config.headers })
        .map(res => res.json()).catch(function(err){
            throw err;
    });
}

addSong(event) 在页面上按下按钮并且所有需要传递的文件正在传递时调用。这里唯一的问题是mp3, lrc, wav, txt 和它们的文件夹一起放在不同的文件夹下,例如vocal.mp3

只是为了说明,这就是我现在得到的:

├───songs
│   ├───vocal
│   │    vocal.mp3
│   ├───pitches
│   │    pitches.txt
...

这就是我需要的:

├───songs
│   ├───title
│   │    vocal.mp3
│   │    lyric.lrc
│   │    pitches.txt
...

和服务器端:

Router.post('/uploadFiles', (req, res) => {

    var title = req.body.title || "title";

    var storage = multer.diskStorage({
        destination: function (req, file, cb) {
            var dir = "../songs/" + file.originalname.split('.')[0];
            if (!fs.existsSync(dir)){
                fs.mkdirSync(dir);
            }
            cb(null, dir);
        },
        filename: function (req, file, cb) {
            cb(null, file.originalname);
        }
    });

    var upload = multer({ storage : storage}).any();
    upload(req,res,function(err){            
        if(err){            
            return res.status(500).send({ 
                code: 500, message: 'could not upload file: ' + err, error: err });
        }else {
            return res.status(200).send({ 
                code: 200, message: 'All files uploaded!', err: ""});
        }                     
    });       
});

【问题讨论】:

    标签: javascript jquery node.js


    【解决方案1】:

    您可以在示例中看到您实际上是这样编码的

    var storage = multer.diskStorage({
        destination: function (req, file, cb) {
            var dir = "../songs/" + file.originalname.split('.')[0];
            if (!fs.existsSync(dir)){
                fs.mkdirSync(dir);
            }
            cb(null, dir);
        },
        filename: function (req, file, cb) {
            cb(null, file.originalname);
        }
    });
    

    file.originalname.split('.')[0] 实际上是拆分扩展名并获取文件名。

    所以它将是var dir = "../songs/" + title; 简单明了。

    var storage = multer.diskStorage({
        destination: function (req, file, cb) {
            ////////////////////////////
            var dir = "../songs/" + title;
            ///////////////////////
            if (!fs.existsSync(dir)){
                fs.mkdirSync(dir);
            }
            cb(null, dir);
        },
        filename: function (req, file, cb) {
            cb(null, file.originalname);
        }
    });
    

    另外,body-parser 不处理多部分正文,这是 FormData 提交的内容。所以req.body.title 将不起作用。

    查看此内容以供参考:How to handle FormData from express 4
    您很可能需要以另一种方式发送title

    【讨论】:

    • 我知道我已经接受了您的回答,但为什么现在文件夹名称总是“标题”。它曾经在插入时获得正确的标题,但现在它始终是“标题”。是不是因为加了一个字符串"title",没有得到`req.body.title"?虽然以前也得到过
    • 你能检查一下console.log(title),看看你是否正确。
    • 已编辑答案,检查它是否回答了您的查询或提出其他问题
    猜你喜欢
    • 1970-01-01
    • 2012-08-17
    • 2010-10-02
    • 2019-12-20
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多