我使用一个指令来设置change 事件的范围变量。
<input type=file my-files="files" /><br>
my-files 指令
app.directive("myFiles", function($parse) {
return function linkFn (scope, elem, attrs) {
elem.on("change", function (e) {
scope.$eval(attrs.myFiles + "=$files", {$files: e.target.files});
scope.$apply();
});
};
});
DEMO on PLNKR。
如何使用 $http 服务发布文件
在对文件进行 POST 时,将 Content-Type header 设置为 undefined 很重要。
var config = { headers: {
"Content-Type": undefined,
}
};
$http.post(url, vm.files[0], config)
.then(function(response) {
vm.result = "SUCCESS";
}).catch(function(response) {
vm.result = "ERROR "+response.status;
});
默认情况下,AngularJS 框架使用内容类型application/json。通过设置Content-Type: undefined,AngularJS 框架省略了内容类型标头,允许XHR API 设置内容类型。
欲了解更多信息,请参阅MDN Web API Reference - XHR Send method
本地下载
使用带有download 属性的<a> 标记:
<a download="{{files[0].name}}" xd-href="data">
<button>Download data</button>
</a>
xd-href 指令:
app.directive("xdHref", function() {
return function linkFn (scope, elem, attrs) {
scope.$watch(attrs.xdHref, function(newVal) {
newVal && elem.attr("href", newVal);
});
};
});
DEMO on PLNKR。