[英]How do I upload images using MongoDB + Node.js (Express.js)?
我也使用Mongoose,如果这是相关的。 我正在尝试允许用户上传个人资料照片。 必须有一个简单的方法,不是吗?
我想你应该尝试一下。
从multer站点简单:
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
app.post('/upload', uploads.any(), function(req,res){
res.send(req.files);
});
它应该在uploads文件夹中(在root下)上传文件,并以JSON格式返回文件。
在此示例中,您将看到如何将要发送的文件存储到服务器目录中,然后从那里拾取并保存它们。 您也可以直接保存它们。 首先你使用angular拾取文件,你可以使用任何东西,如果你想,你可以在这里查看更多细节。 这是我的小例子,代码是玉。
<input type="file" name="file" onchange="angular.element(this).scope().selectFile(this.files)"/>
<button ng-click="savePhoto()">Save </button>
在你的角度控制器
$scope.savePhoto = function () {
var fd = new FormData();
fd.append("file", $scope.files[0]);
)) ;
$http.post("/xxx/photos", fd, {
withCredentials: true,
headers: { 'Content-Type': undefined },
transformRequest: angular.identity
}).success(function (data) {
$scope.image = data; // If you want to render the image after successfully uploading in your db
});
};
在后端使用npm安装multer。 然后在app.js中你可以设置一个中间件来收集你发送的文件。只需在这里做console.log(req)来检查你是否在这里获取文件。 Multer在这里发挥了魔力。
app.use(multer({
dest: path.join(__dirname, 'public/assets/img/profile'),
rename: function (fieldname, filename, req, res) {
console.log(req)// you will see your image url etc.
if(req.session.user) return req.session.user.id;
}
}));
所以这里的图像将存储在服务器的这个路径(public / assets / img / profile)中。 现在,您从此服务器获取文件并添加到您的数据库。
var path = require('path');
var imgPath =path.join(__dirname, '../public/assets/img/profile/' + id + '.jpg'); // this is the path to your server where multer already has stored your image
console.log(imgPath);
var a ;
a = fs.readFileSync(imgPath);
YourSchema.findByIdAndUpdate( id, {
$set:
{'img.data' : a,
'img.contentType' : 'image/png' }
}, function(err, doc) {
if (err)console.log("oi");
}
);
//In case you want to send back the stored image from the db.
yourSchema.findById(id, function (err, doc) {
if (err)console.log(err);
var base64 = doc.img.data.toString('base64');
res.send('data:'+doc.img.contentType+';base64,' + base64);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.