我需要一些帮助。我需要将文件保存到文件夹中,并希望使用Node.js将该文件的名称保存到数据库中。我在下面解释我的代码。
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, file.fieldname + '-' + Date.now());
}
});
exports.saveCardDetails=function(upload.single('image'),req,res){
var name=req.body.name;
var company=req.body.company;
var position=req.body.position;
var mobile=req.body.mobile;
var email=req.body.email;
var landline=req.body.landline;
var url=req.body.url;
var postcode=req.body.postcode;
var address=req.body.address;
var image=req.body.image;
var userid=req.body.userid;
var profiletext=req.body.profile;
var biography=req.body.biography;
var token_id=req.body.token_id;
console.log('request',req);
}
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=8989;
var admin=require('./route/route.js');
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 })) // parse application/x-www-form-urlencoded
app.use(bodyParser.json()) // parse application/json
app.post('/api/users/save-card-details',api.saveCardDetails);
在此之后我收到以下错误。
错误:
POST /api/users/save-card-details 413 13.277 ms - 1120
Error: request entity too large
at readStream (/opt/lampp/htdocs/heroku/FGDP/node_modules/raw-body/index.js:196:17)
at getRawBody (/opt/lampp/htdocs/heroku/FGDP/node_modules/raw-body/index.js:106:12)
at read (/opt/lampp/htdocs/heroku/FGDP/node_modules/body-parser/lib/read.js:76:3)
at urlencodedParser (/opt/lampp/htdocs/heroku/FGDP/node_modules/body-parser/lib/types/urlencoded.js:115:5)
at Layer.handle [as handle_request] (/opt/lampp/htdocs/heroku/FGDP/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/opt/lampp/htdocs/heroku/FGDP/node_modules/express/lib/router/index.js:312:13)
at /opt/lampp/htdocs/heroku/FGDP/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/opt/lampp/htdocs/heroku/FGDP/node_modules/express/lib/router/index.js:330:12)
at next (/opt/lampp/htdocs/heroku/FGDP/node_modules/express/lib/router/index.js:271:10)
at logger (/opt/lampp/htdocs/heroku/FGDP/node_modules/morgan/index.js:144:5)
我在这里获取图片并需要保存到文件夹中。保存到文件夹后,我需要将文件名保存到exports.saveCardDetails
函数中。我的文件夹结构如下所示。
--> api/api.js
--> upload
我正在使用multer
npm包。请帮我这样做。
答案 0 :(得分:0)
看起来multer因文件大小而失败。
尝试在multer配置中设置fieldSize变量,如下所示 -
multer({
storage: storage,
limits: { fileSize: maxSize }
})
您可以在此处找到这些设置 - https://www.npmjs.com/package/multer(搜索限制)。 希望这有帮助!