2016-09-06 125 views
1

我想使用Multer上傳多個圖像。除了僅上傳一個文件(所選最後一個文件)之外,它全部按預期工作。使用Multer上傳多個文件

HTML

<form class='new-project' action='/projects' method='POST' enctype="multipart/form-data"> 
    <label for='file'>Select your image:</label> 
    <input type='file' multiple='multiple' accept='image/*' name='uploadedImages' id='file' /> 
    <span class='hint'>Supported files: jpg, jpeg, png.</span> 
    <button type='submit'>upload</button> 
</form> 

JS

//Define where project photos will be stored 
var storage = multer.diskStorage({ 
    destination: function (request, file, callback) { 
    callback(null, './public/uploads'); 
    }, 
    filename: function (request, file, callback) { 
    console.log(file); 
    callback(null, file.originalname) 
    } 
}); 

// Function to upload project images 
var upload = multer({storage: storage}).any('uploadedImages'); 

// add new photos to the DB 
app.post('/projects', function(req, res){ 
    upload(req, res, function(err){ 
    if(err){ 
     console.log('Fucken bollocks'); 
     console.log(err); 
     return; 
    } 
    console.log(req.files); 
    res.end('Your files uploaded. Fuck yeah!!'); 
    console.log('Yep yep!'); 
    }); 
}); 

我得到我想的東西很明顯的感覺......

編輯

代碼我嘗試以下賽義德的幫助:

HTML

<label for='file'>Select your image:</label> 
<input type='file' accept='image/*' name='uploadedImages' multiple/> 
<span class='hint'>Supported files: jpg, jpeg, png.</span> 
<input type="submit" value="uploading_img"> 

JS

multer = require('multer'), 

var upload = multer(); 

app.post('/projects', upload.array('uploadedImages', 10), function(req, res, err) { 
if (err) { 
    console.log('error'); 
    console.log(err); 
} 
var file = req.files; 
res.end(); 
console.log(req.files); 

});

回答

0

在這裏,你去下面這個例子:

var multer = require('multer'); 
var upload = multer(); 

router.post('/projects', upload.array('uploadedImages', 10), function(req, res) { 
    var file = req.files; 
    res.end(); 
}); 

<form action="/projects" method="post" enctype="multipart/form-data"> 
    <input type="file" name="uploadedImages" value="uploading_img" multiple> 
    <input type="submit" value="uploading_img"> 
</form> 

訪問以獲取更多信息關於Multer

+0

感謝賽義德,但我只是嘗試這樣做,收到此錯誤控制檯:錯誤 '[功能:下一頁] [{字段名: 'uploadedImages', ORIGINALNAME: 'Me.jpg', 編碼: '7位' , mimetype:'image/jpeg', buffer:, size:98305}]' –

+0

您是否只嘗試過我的示例或應用您的代碼? – Noman

+0

我剛剛添加了我嘗試添加到原始文章中的代碼。與你的相同或多或少,但它不起作用。 –

0

我的猜測是,你要上傳的每個文件,你reclick:

<input type='file' multiple='multiple' accept='image/*' name='uploadedImages' id='file' /> 

如果你這樣做,那麼只有最後一次選擇的文件將會被上傳,因爲你覆蓋以前選定的文件。

要上傳多個文件,您必須在文件選取器中一次全選所有文件。