如何从路由器文件中引用“public”静态文件夹中的文件夹?

时间:2015-12-03 23:49:49

标签: node.js express path public multer

我正在尝试从路由器引用tracks_folder文件夹中名为public的文件夹。

我项目的简化结构如下

app.js
routes/ 
      tracks/
            router.js
public/
      tracks_folder/

基本上我想从router.js引用tracks_folder,以便将文件上传到该文件夹​​,但我无法做到。

我尝试过:

  1. ../../public/tracks_folder/
  2. ../../tracks_folder/
  3. ./tracks_folder/
  4. 但它们都不起作用。在我的app.js我有

    app.use(express.static(path.join(__dirname, 'public')));
    

    但是例如对于第三种情况,我收到以下错误:

    Error: ENOENT: no such file or directory, open 'tracks_folder/aaa.mp3'
    

    出现错误(原生)

    理论上我应该能够至少使用第一种方法引用tracks_folder文件夹,但它确实有效。

    我正在使用multer上传文件及其磁盘存储来存储它们......

    以下是router.js中简化的与问题相关的代码:

    ...
    var multer = require('multer')
    var uploadFolder = "./tracks_folder/";
    
    function formatTrackName(originalName) {
      return originalName.replace(/\s+/g, '-').toLowerCase();
    }
    
    var trackStorage = multer.diskStorage({
      // used to determine within which folder the uploaded files should be stored.
      destination: function(req, file, callback) {
    
        callback(null, uploadFolder);
      },
    
      filename: function(req, res, callback) {
        // req.body.name should contain the name of track
        callback(null, formatTrackName(req.body.name) + ".mp3");
      }
    });
    
    
    var upload = multer({
      storage: trackStorage
    })
    
    ...
    ...
    

    这是我未实现的帖子方法:

    router.post('/upload', upload.single("track"), function(req, res) {
    
    });
    

1 个答案:

答案 0 :(得分:0)

尝试 ./ public / tracks_folder
它对我有用