我希望能够在保存文档本身的同时上传附件(例如,不是在文档已经存在之后)。
角度应用程序从设计文档HTML附件中提供,并依赖于ngResource
。我为CouchDB文档创建了一个工厂(简称coffeescript中的示例):
factory('Resource', ['$resource', ($resource) ->
$resource '/mydb/:id', {id: '@_id', rev: '@_rev'}, update: method: 'PUT'])
和指令(来自here):
directive('fileModel', ['$parse', ($parse) ->
restrict: 'A'
link: (scope, elem, attrs) ->
elem.bind 'change', -> scope.$apply ->
$parse(attrs.fileModel).assign scope, elem[0].files[0] ])
和表单输入:
<input type="file" file-model="attachment" accept="image/*">
I've read在new Resource
之后,我可以附加到._attachments
- 哈希表单中的新对象:
attachment.filename: { content_type: attachment.type, data: btoa attachment }
而btoa
和FileReader
解决方案代替FormData
的不同变体。
但我还没有能够让他们中的任何一个工作。
您知道这是否可能,或者我是否应该仅在创建文档后才进行文件上传?
答案 0 :(得分:1)
得到了风滚草徽章,所以这里有一个自我回答。
有很多方法,但这是我开始工作的一种方式。基本上需要来自浏览器的FileReader
,并剥离base64&#34;标题&#34;:
directive('fileread', ->
scope: fileread: '='
link: (scope, elem, attrs) ->
scope.fileread = {}
elem.bind 'change', (change) ->
[].slice.apply(change.target.files).forEach (image) ->
hdrln = ('data:;base64,' + image.type).length
reader = new FileReader()
reader.onloadend = (load) -> scope.$apply ->
scope.fileread[image.name] =
content_type: image.type
data: load.target.result.slice hdrln
reader.readAsDataURL image
)
可以使用以下形式:
<input type="file" fileread="images" accept="image/*" multiple>
之后,控制器中将有一个变量$scope.images
,您可以将其放入父文档对象中:$scope.doc._attachments = $scope.images
。