AngularJS:如何实现与多部分组成一个简单的文件上传? [英] AngularJS: how to implement a simple file upload with multipart form?
问题描述
我想从AngularJS做一个简单的多部分表单提交到服务器的node.js,
的形式应当包含在一个部分JSON对象和图像中的其他部分,
(我目前只发布了JSON对象,$资源)
I want to do a simple multipart form post from AngularJS to a node.js server, the form should contain a JSON object in one part and an image in the other part, (I'm currently posting only the JSON object with $resource)
我想我应该输入类型=文件开始,但随后发现,AngularJS不能绑定到该..
I figured I should start with input type="file", but then found out that AngularJS can't bind to that..
所有我能找到的例子是用于包木窗拖动和放jQuery插件;下降。我想要一个文件的一个简单的上传
all the examples I can find are for wraping jQuery plugins for drag & drop. I want a simple upload of one file.
我是新来AngularJS和不舒服的所有写我自己的指令。
I'm new to AngularJS and don't feel comfortable at all with writing my own directives.
推荐答案
没有其他的依赖比angularjs一个真正的工作解决方案(与1.0.6版测试)
A real working solution with no other dependencies than angularjs (tested with v.1.0.6)
HTML
<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>
Angularjs(1.0.6)不支持的 NG-模型的关于输入文件标签,所以你必须这样做,在传递的所有(最终)一个本地通所选文件从用户
Angularjs (1.0.6) not support ng-model on "input-file" tags so you have to do it in a "native-way" that pass the all (eventually) selected files from the user.
控制器
$scope.uploadFile = function(files) {
var fd = new FormData();
//Take the first selected file
fd.append("file", files[0]);
$http.post(uploadUrl, fd, {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).success( ...all right!... ).error( ..damn!... );
};
凉爽的部分是未定义的内容类型和的 transformRequest:angular.identity 的,让在$ HTTP来选择合适的内涵式的能力和处理多数据时,需要管理的边界。
The cool part is the undefined content-type and the transformRequest: angular.identity that give at the $http the ability to choose the right "content-type" and manage the boundary needed when handling multipart data.
这篇关于AngularJS:如何实现与多部分组成一个简单的文件上传?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!