【发布时间】:2016-07-10 10:25:19
【问题描述】:
我在我的注册表单中使用了一个文件输入。当点击提交按钮时,用户被添加到数据库并开始文件上传。
在我的 html 表单中,我正在使用 onchange 函数,但是每当文件更改时,控制台都会给出一个错误,指出该函数未定义
控制器:
var vm = this;
$scope.setFile = function(element) {
$scope.$apply(function() {
$scope.theFile = element.files[0];
console.log($scope.theFile)
});
}
$scope.signup = function () {
$http
.post('/api/usersignup', vm.userData)
.then(function (data) {
if (data) {
uploadImage(data.userId, $scope.theFile)
}
else {
console.log("null");
}
})
};
function uploadImage(userId, fileData) {
console.log('user----------->'+userId+"------------------>"+fileData)
$http
.post('/api/testupload', userId, fileData)
.then(function (data) {
})
}
用户注册API
api.post('/usersignup', function(req, res) {
var name = req.body.name,
email = req.body.email,
password = req.body.password;
var newUser = new User({
name: name,
email: email,
password: password,
tag: 'user'
});
nev.createTempUser(newUser, function(err, newTempUser) {
if (err) {
return res.status(404).send(err);
}
// new user created
if (newTempUser) {
var URL = newTempUser[nev.options.URLFieldName];
nev.sendVerificationEmail(email, URL, function(err, info) {
if (err) {
console.log(err);
return res.status(404).send(err);
}
res.json({
msg: 'An email has been sent to you. Please check it to verify your account.',
info: info
});
});
// user already exists in temporary collection!
} else {
res.json({
msg: 'You have already signed up. Please check your email to verify your account.'
});
}
});
});
图片上传到s3的api
api.post('/testupload', function(req , res) {
userId = req.body.userId;
async.waterfall([
function(done) {
crypto.randomBytes(50, function(err, buf) {
var photoid = buf.toString('hex') + '.png';
done(err, photoid);
});
},
function(photoid, done) {
var file = req.body.fileData;
var stream = fs.createReadStream(file.path);
return s3fsImpl.writeFile(photoid, stream).then(function(err){
fs.unlink(file.path, function(err){
if(err)
console.log(err);
})
var imgid = photoid;
res.json(photoid);
})
}
])
});
html代码在这里:
<div class="container" ng-controller="UserCreateController as user">
<form class="form-sigin" method="post" ng-submit="signup()" enctype="multipart/form-data" >
Name: <input type="text" name="name" class="form-control" ng-model="user.userData.name">
email: <input type="text" name="email" class="form-control" ng-model="user.userData.email">
Password: <input type="password" name="password" class="form-control" ng-model="user.userData.password">
<input type="file" name="file" onChange="setFile(this)">
<button type="submit" class="btn btn-danger" >Signup</button>
</form>
</div>
【问题讨论】:
标签: javascript html angularjs node.js