1

我想使用 angularjs 处理文件上传。我已经建立了控制器中包含的模型、视图、控制器和服务:

#Model
window.App.factory 'RepositoryItem', (railsResourceFactory) ->
  railsResourceFactory
    url: '/api/repository_items/{{_id && _id.$oid}}'
    name: 'repository_item'

#Service
window.App.service 'fileUpload', (RepositoryItem) ->
  this.files = {}

  this.remove = (field) =>
    itemToRemove = field.value
    if (itemToRemove)
      field.value.remove().then ->
        index = field.items.indexOf itemToRemove
        field.items.splice index, 1
        field.value = field.items[0]

  this.init = (task, field) =>
    # IT WORKS
    RepositoryItem.query({
      realm: task.variables.realm, criterion:{taskId: task.id, formType: field.id}
    }).then (fileItems) =>
      this.files[field.id] = fileItems

  this.upload = (task, field, element) =>
    for file in element.files
      reader = new FileReader()
      reader.onload = (event) =>

        # IT DOES NOT WORK
        new RepositoryItem({
          formType: field.id, taskId: task.id, content: event.target.result, name: file.name
        }).create().then (newItem) =>
          console.log 'newItem'
          console.log newItem
          this.rootScope.$apply =>
            this.files[field.id].push newItem

      reader.readAsBinaryString file

#View
<script type="text/ng-template" id="fileUpload">
<div class="field">
  <table class='attachments' ng-init="fileUpload.init(task, f)">
    <tr>
      <td> Attachments </td>
      <td></td>
    </tr>
    {{ fileUpload.files }}
    <tr ng-repeat="file in fileUpload.files[f.id]">
      <td> {{file.name}} </td>
      <td> XXX </td>
    </tr>
  </table>
  <input type="file" multiple onchange="angular.element(this).scope().fileUpload.upload({{task}}, {{f}}, this)"/>
</div>
</script>

在上传方法中,我尝试创建新的 RepositoryItem。此方法应该向服务器发送请求(就像在 init 操作中所做的那样),但它不发送任何请求。我该如何解决?

更新1:

我已经跟踪了 rails-angular-resource 的嵌套调用。它调用 $http(config) 但在网络控制台和我的服务器中都没有跟踪任何请求。

4

0 回答 0