2014-09-06 57 views
6

我試圖上傳任何文件使用Multer package。當我在我的server.js文件中使用以下代碼時,它工作正常。如何使用multer在nodejs中設置不同的目的地?

var express = require('express'), 
    app = express(), 
    multer = require('multer'); 
app.configure(function() { 
    app.use(multer({ 
     dest: './static/uploads/', 
     rename: function (fieldname, filename) { 
      return filename.replace(/\W+/g, '-').toLowerCase(); 
     } 
    })); 
    app.use(express.static(__dirname + '/static')); 
}); 

app.post('/api/upload', function (req, res) { 
    res.send({image: true, file: req.files.userFile.originalname, savedAs: req.files.userFile.name}); 
}); 

var server = app.listen(3000, function() { 
    console.log('listening on port %d', server.address().port); 
}); 

我想要的是將文件存儲在不同的位置。我曾嘗試下面的代碼,但它不適合我。

var express = require('express'), 
    app = express(), 
    multer = require('multer'); 
app.configure(function() { 
    app.use(multer({ 
     //dest: './static/uploads/', 
     rename: function (fieldname, filename) { 
      return filename.replace(/\W+/g, '-').toLowerCase(); 
     } 
    })); 
    app.use(express.static(__dirname + '/static')); 
}); 

app.post('/api/pdf', function (req, res) { 
    app.use(multer({ dest: './static/pdf/'})); 
    res.send({image: true, file: req.files.userFile.originalname, savedAs: req.files.userFile.name}); 
}); 

app.post('/api/image', function (req, res) { 
    app.use(multer({ dest: './static/image/'})); 
    res.send({image: true, file: req.files.userFile.originalname, savedAs: req.files.userFile.name}); 
}); 

app.post('/api/video', function (req, res) { 
    app.use(multer({ dest: './static/video/'})); 
    res.send({image: true, file: req.files.userFile.originalname, savedAs: req.files.userFile.name}); 
}); 

var server = app.listen(3000, function() { 
    console.log('listening on port %d', server.address().port); 
}); 

手段,如果我打http://localhost:3000/api/pdf文件應在「PDF」文件夾中存儲,如果我打http://localhost:3000/api/video文件應在「視頻」文件夾中存儲。

有什麼辦法可以達到這個目的嗎?

預先感謝您。

+0

截至目前,'multer'是不可能的。 https://github.com/expressjs/multer/issues/58這是我從'所有者'得到的答覆。 – AkshayP 2014-09-11 07:08:55

+4

解決 - https://github.com/jpfluger/multer/blob/examples/multer-upload-files-to-different-directories.md – AkshayP 2014-09-29 05:08:26

回答

9

更新

,因爲我張貼了原來的答覆相當多的事情已經改變。使用multer 1.2.1

  1. 您需要使用DiskStorage指定其中 & 如何存儲的文件的
  2. 默認情況下,multer將使用操作系統的默認目錄。在我們的情況下,因爲我們對位置特別感興趣。我們需要確保文件夾存在,然後才能將文件保存在那裏。

注意:當提供目的地作爲函數時,您負責創建目錄。

更多here

'use strict'; 

let multer = require('multer'); 
let fs = require('fs-extra'); 

let upload = multer({ 
    storage: multer.diskStorage({ 
    destination: (req, file, callback) => { 
     let type = req.params.type; 
     let path = `./uploads/${type}`; 
     fs.mkdirsSync(path); 
     callback(null, path); 
    }, 
    filename: (req, file, callback) => { 
     //originalname is the uploaded file's name with extn 
     callback(null, file.originalname); 
    } 
    }) 
}); 

app.post('/api/:type', upload.single('file'), (req, res) => { 
    res.status(200).send(); 
}); 

fs-extra創建目錄,just in case if it doesn't exists

原來的答覆

您可以使用changeDest

重命名放置上傳文件的目錄的功能。

它是自v0.1.8

app.post('/api/:type', multer({ 
dest: './uploads/', 
changeDest: function(dest, req, res) { 
    var newDestination = dest + req.params.type; 
    var stat = null; 
    try { 
     stat = fs.statSync(newDestination); 
    } catch (err) { 
     fs.mkdirSync(newDestination); 
    } 
    if (stat && !stat.isDirectory()) { 
     throw new Error('Directory cannot be created because an inode of a different type exists at "' + dest + '"'); 
    } 
    return newDestination 
} 
}), function(req, res) { 
    //set your response 
}); 
+0

謝謝。它的工作原理 – 2015-04-17 09:01:15

8

Multer是一箇中間件,所以你可以通過這樣的:

app.post('/test/route', multer({...options...}), module.someThing) 

app.post('/test/route', multer({...options...}), function(req, res){ 
........some code ...... 
}); 
1

,您可以撥打功能,像這樣:

var uploadFnct = function(dest){ 
     var storage = multer.diskStorage({ //multers disk storage settings 
      destination: function (req, file, cb) { 
       cb(null, './public/img/'+dest+'/'); 
      }, 
      filename: function (req, file, cb) { 
       var datetimestamp = Date.now(); 
       cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1]); 
      } 
     }); 

     var upload = multer({ //multer settings 
         storage: storage 
        }).single('file'); 

     return upload; 
    }; 

,然後在上傳航線使用它:

//Handle the library upload 
    app.post('/app/library/upload', isAuthenticated, function (req, res) { 
     var currUpload = uploadFnct('library'); 
     currUpload(req,res,function(err){ 
      if(err){ 
       res.json({error_code:1,err_desc:err}); 
       return; 
      } 
      res.json({error_code:0,err_desc:null, filename: req.file.filename}); 
     }); 
    }); 
+0

當提供'destination'作爲函數時,您負責創建目錄。傳遞字符串時,multer會確保爲您創建目錄。 – Bishan 2016-09-09 05:21:30

+0

它的作品非常感謝你:) – CELB 2018-01-16 19:57:14

0

我嘗試了這裏顯示的解決方案,但沒有任何幫助我。

ChangeDest attr爲不再可用(如斯里達爾在他的回答中提出)

,我想分享我的解決方案(我用快遞4.13和multer 1.2):

進口

var express = require('express'); 
var router = express.Router(); 
var fs = require('fs'); 
var multer = require('multer'); 


存儲變量(參見文檔here

var storage = multer.diskStorage({ 
    destination: function (req, file, cb) { 
     var dest = 'uploads/' + req.params.type; 
     var stat = null; 
     try { 
      stat = fs.statSync(dest); 
     } catch (err) { 
      fs.mkdirSync(dest); 
     } 
     if (stat && !stat.isDirectory()) { 
      throw new Error('Directory cannot be created because an inode of a different type exists at "' + dest + '"'); 
     }  
     cb(null, dest); 
    } 
}); 


初始化Multer:

var upload = multer(
    { 
     dest: 'uploads/', 
     storage: storage 
    } 
); 


使用它!

router.use("/api/:type", upload.single("obj")); 
router.post('/api/:type', controllers.upload_file); 
0
var storage = multer.diskStorage({ 
    destination: function (req, file, cb) { 
    if (req.path.match('/pdf')) { 
     cb(null,<destination>) 
    } 
    }, 
    filename: function (req, file, cb) { 
    } 
}) 

這工作的情況下,該路徑是唯一的。您可以根據需要修改(檢查終點{req.path})。雖然這個解決方案不是動態的。

相關問題