Cac*_*cos 19 mongodb node.js express angularjs mean-stack
我最近开始使用MEAN Stack编程,我目前正在实现某种社交网络.一直在使用MEAN.io框架来做到这一点.我现在的主要问题是让文件上传工作,因为我想要做的是从表单接收文件到AngularJS控制器并将其与更多信息一起传递给ExpressJS,这样我最终可以将所有内容发送到MongoDB.(我正在构建一个注册新用户表单).
我不想将文件本身存储在数据库中,但我想存储一个链接.
我在google上用不同的搜索查询搜索了几十页,但我找不到任何我能理解或工作的内容.一直在寻找没有结果的时间.这就是我来到这里的原因.
谁能帮我这个?
谢谢 :)
编辑:也许一些代码将有助于理解.
我作为基础使用的默认MEAN.io Users Angular控制器具有以下功能:
$scope.register = function(){
$scope.usernameError = null;
$scope.registerError = null;
$http.post('/register', {
email: $scope.user.email,
password: $scope.user.password,
confirmPassword: $scope.user.confirmPassword,
username: $scope.user.username,
name: $scope.user.fullname
})//... has a bit more code but I cut it because the post is the main thing here.
};
Run Code Online (Sandbox Code Playgroud)
我想要做的是:从表单接收文件到这个控制器并将其与电子邮件,密码,名称等一起传递,并且能够使用位于服务器端的expressjs上的json.'/ register'是一个nodejs路由,因此服务器控制器创建用户(使用用户模式)并将其发送到MongoDB.
ken*_*dds 25
我最近做了这样的事情.我使用了angular-file-upload.您还希望端点的节点多方解析表单数据.然后你可以使用s3将文件上传到s3.
这是我编辑的一些代码.
角度模板
<button>
Upload <input type="file" ng-file-select="onFileSelect($files)">
</button>
Run Code Online (Sandbox Code Playgroud)
角度控制器
$scope.onFileSelect = function(image) {
$scope.uploadInProgress = true;
$scope.uploadProgress = 0;
if (angular.isArray(image)) {
image = image[0];
}
$scope.upload = $upload.upload({
url: '/api/v1/upload/image',
method: 'POST',
data: {
type: 'profile'
},
file: image
}).progress(function(event) {
$scope.uploadProgress = Math.floor(event.loaded / event.total);
$scope.$apply();
}).success(function(data, status, headers, config) {
AlertService.success('Photo uploaded!');
}).error(function(err) {
$scope.uploadInProgress = false;
AlertService.error('Error uploading file: ' + err.message || err);
});
};
Run Code Online (Sandbox Code Playgroud)
路线
var uuid = require('uuid'); // https://github.com/defunctzombie/node-uuid
var multiparty = require('multiparty'); // https://github.com/andrewrk/node-multiparty
var s3 = require('s3'); // https://github.com/andrewrk/node-s3-client
var s3Client = s3.createClient({
key: '<your_key>',
secret: '<your_secret>',
bucket: '<your_bucket>'
});
module.exports = function(app) {
app.post('/api/v1/upload/image', function(req, res) {
var form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
var file = files.file[0];
var contentType = file.headers['content-type'];
var extension = file.path.substring(file.path.lastIndexOf('.'));
var destPath = '/' + user.id + '/profile' + '/' + uuid.v4() + extension;
var headers = {
'x-amz-acl': 'public-read',
'Content-Length': file.size,
'Content-Type': contentType
};
var uploader = s3Client.upload(file.path, destPath, headers);
uploader.on('error', function(err) {
//TODO handle this
});
uploader.on('end', function(url) {
//TODO do something with the url
console.log('file opened:', url);
});
});
});
}
Run Code Online (Sandbox Code Playgroud)
我从我的代码中更改了这个,所以它可能无法开箱即用,但希望它有用!
| 归档时间: |
|
| 查看次数: |
21789 次 |
| 最近记录: |