Multer and AngularJS
Multer and AngularJS
我不知道如何通过angular $http发布。为什么?我想multer解析和存储我的文件和角得到一个副本,当它完成。更棒的是,我想让angular获取一个副本,然后把它传递给服务器。
我可以使用下面的代码片段上传一个文件:
// view (jade)
.container
form(action="/upload", method="POST", enctype="multipart/form-data")
input(type="file", name="f")
input(type="submit", value="Upload")
// post route (express)
var multer = require('multer');
var upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('f'), function(req, res) {
console.log(req.file);
});
使用任何示例文件运行此命令,将返回我想要的json到控制台,并且图像成功地存储在适当的目录中。然而:
// view (jade)
form(enctype="multipart/form-data" ng-submit="uploadFile(file)")
input(type="file", name="f", ng-model="file")
input(type="submit", value="Upload")
// ctrl (angular)
$scope.uploadFile = function(file) {
console.log(file);
$http.post('/upload', file);
};
// post route (express)
var multer = require('multer');
var upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('f'), function(req, res) {
console.log(req.file);
});
这在两个控制台输入上都返回undefined,即使我没有更改文件,我只更改了它的发送方式。
这让我相信两件事中的一件:
提交的数据不是我想的那样。如果是这样,那是什么?日志上没有打印。
或
提交的数据会被angular以某种方式改变。如果是这样,怎么会这样呢?同样,日志上没有打印任何内容。
在第一种情况下,通过将数据直接通过表单发送到服务器,您让html在底层执行转换魔术。
在第二种情况下,通过AngularJs通过$http发送,你需要告诉中间件,这是$http,它需要对请求进行必要的转换,以匹配你传递给表单的属性。
由于我自己已经为此挣扎了一段时间,这里是我使用的代码的改编(用于$resource)。但我认为它应该为底层的$http.
工作。所以在控制器中:
$scope.uploadFile = function(file) {
console.log(file);
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined},
enctype: 'multipart/form-data'
}
})
.success(function(){
})
.error(function(){
});
};
要使其工作,您需要将文件输入字段绑定到模型。当然,由于某些原因,Angularjs并没有选择这样做。
在玉景中:
form(enctype="multipart/form-data" ng-submit....)
input(type="file", name="f", ng-model="file" on change='angular.element(this).scope().readFile(this)')
input(type="submit", value="Upload")
onchange
是JavaScript而不是AngularJs,它触发了我们需要定义的scope.readfile()函数:
在控制器中:
$scope.readfile = function(elem) {
var file= elem.files[0];
var reader = new FileReader();
reader.onload = function() {
$scope.$apply(function(){
$scope.file = file;
$scope.imageUrl = reader.result // to display image via ng-Src
})
}
reader.readAsDataURL(file);
}
我认为在处理表单时,应该把一些html的魔力带回angular。
我建议你看看JavaScript的onchange
, FormData
和FileReader
的代码片段,像这些和更好的文档。
- Upload with angularjs and rails 4
- AngularJS and models
- AngularJS and jQuery alert
- AngularJS and sidr library
- Angularjs and web services
- AngularJS and Cross Domain POST
- AngularJS and Packery
- AngularJS and Select
- AngularJS and adsense
- AngularJS and 508 standards
- AngularJS and SEO clarification
- CRUD with AngularJS and PHP
- Javascript, AngularJS and setTimeout function
- AngularJS and location.path()
- BrainTree.js with AngularJS and customVariables
- AngularJS and Django permissions
- AngularJS and javascript oop
- AngularJS and Animations
- AngularJS and Webpack Integration
- Angularjs and pusher socket_id