我尝试使用Mongoose,Express和Angular上传和存储图片。我在这里选择了下一个解决方案:
.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('change', function(){
$parse(attrs.fileModel).assign(scope,element[0].files)
scope.$apply();
});
}
};
}])
控制器中的下一个功能:
$scope.uploadFile=function(){
var fd = new FormData();
angular.forEach($scope.files,function(file){
fd.append('file',file);
});
$http.post('http://' + host + ':3000/users/' + $scope.selectedTask._id,fd,
{
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function(d){
console.log('yes');
})
}
和html:
<input type = "file" file-model="files" multiple/>
<button ng-click = "uploadFile()">upload me</button>
<li ng-repeat="file in files">{{file.name}}</li>
但由于某些原因,我在我的端点中获取的是一个空的请求对象。我在express.js中使用以下代码检查它:
user.route('/users/:id')
.post(function (req, res, next) {
console.log(req.body);
})
我认为问题在于我不知道如何存储大于16MB的东西。
答案 0 :(得分:0)
在此示例中,您将看到如何将要发送的文件存储到服务器目录中,然后从那里获取并保存它们。您也可以直接保存它们。 首先,如果您愿意,可以使用角度拾取文件 check here了解更多详情。 这是我的小例子,代码是玉。
input(type="file" name="file" onchange="angular.element(this).scope().selectFile(this.files)")
button(ng-click='savePhoto()') Save
在角度控制器中
$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);
});
在架构中,以Buffer
类型存储图像img: { data: Buffer}