angular中文件表单的模型和数据绑定、上传方法
angular (1.x)中,模板如下
<input type="file" ng-model="data.file" >
是无法绑定到Controller中的变量 ($scope.data.file) 的。如何解决?使用 angular-file-model [1] 之后,就可以在模板中用下面的形式
<input type="file" file-model="data.file" >
当选定文件后, $scope.data.file 就会成为一个 File object。
但是如何及时预览图像呢?
这个问题可参考 [2] ,自定一个新的 directive,把文件内容读出来,并以dataUrl的形式保存在浏览器内存中,然后绑定到 <img> 标签里面。
第3个问题,如何将文件内容通过HTTP Post的方式发送给某个服务呢?应该构造一个Form对象,并且设置 $http 的 transferRequest 选项为 identity, Content-Type 为 undefined, 参考 [3] 。
[1] | https://github.com/ghostbar/angular-file-model |
[2] | https://stackoverflow.com/questions/17063000/ng-model-for-input-type-file |
[3] | https://stackoverflow.com/questions/13963022/angularjs-how-to-implement-a-simple-file-upload-with-multipart-form |