我需要一个帮助。我使用Postman发送文件,我需要使用Node.js将其上传到必需的文件夹中。我在下面解释我的代码。
server.js:
var express=require('express');
var morgan = require('morgan');
var http=require('http');
var bodyParser= require('body-parser');
var methodOverride = require('method-override');
var mongo = require('mongojs');
var session = require('express-session');
var app=module.exports=express();
var server=http.Server(app);
var port=8889;
var api=require('./api/api.js');
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({ extended: false,limit: '5mb' })) // parse application/x-www-form-urlencoded
app.use(bodyParser.json({limit: '5mb'})) // parse application/json
app.use(methodOverride());
app.post('/upload',api.upload);
server.listen(port);
console.log("Server is running on the port"+port);
api.js:
var multer = require('multer');
var storage =multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './../uploads');
},
filename: function (req, file, callback) {
callback(null, Date.now()+'-'+file.originalname);
}
});
var upload = multer({ storage: storage});
exports.upload=function(req,res){
}
实际上我使用postman
发布文件,其屏幕截图如下所示。
此处我的要求是文件将上传到所需的文件夹i.e-uploads
,并且上传的文件名将作为对用户的响应返回。请帮帮我。
答案 0 :(得分:2)
你还没有在这里使用过滤器。您已使用multer创建了上传,但未使用它。
请尝试以下代码:
app.post('/upload', upload.single('file'), function (req, res, next) {
// req.file is the `file` file
// req.body will hold the text fields, if there were any
})
其中upload将是var upload = multer({storage:storage});变量