(自我问答)如何设置和使用 MULTER 中间件)进行单个文件上传(Expressjs/Nodejs)



只是想发布一个关于如何在 Expressjs/Nodejs 中设置和使用 MULTER 中间件的初学者问题的答案

Hope this saves your time

应该有两个文件:

1.翡翠文件(其中应包含假设索引.翡翠的形式(

2.JS 文件(位于 routes 文件夹中,并定向到 views 文件夹中的 index.jade 文件(

设置索引.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(输入应具有可在索引.js文件中访问的名称属性

设置JS路由文件(索引.js(不在应用程序中.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
})

最新更新