想要在如何设置和使用Expressjs / Nodejs中的MULTER MIDDLEWARE
上发布初学者级别问题的答案答案 0 :(得分:0)
Hope this saves your time
应该有两个文件:
1.Jade文件(应包含表格,假设为index.jade)
2.JS文件(位于routes文件夹中,并指向views文件夹中的index.jade文件)
SETUP index.jade文件
//not a jade file so convert it to jade
//enctype is set to multipart/form-data --- multer requirement
<form method="post" role="form" enctype="multipart/form-data">
<div class="form-group">
<label for="upload">Email address:</label>
//name attribute to access in index.js route file
<input type="file" class="form-control" name="upload" id="upload">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
//非常重要
(a)在Jade文件中,表单必须包含enctype =“multipart / form-data”的属性
(b)输入应具有名称属性,可在index.js文件中访问
SETUP JS ROUTE FILE(index.js)不在app.js
中var express = require('express')
var multer = require('multer')
var upload = multer({ dest: 'uploads/' }) //set dest to where you want to upload the file
var app = express()
// SINGLE FILE UPLOAD
app.post('/', upload.single('upload'), function (req, res, next) {
//since we are performing a single file upload req.file will be used and not req.files
// req.file would attach the file with upload fieldname ~ upload is the name attribute given in the form
//now use req.file to access the file
//for example
console.log(req.file); // this would display the file attributes in the log
})