【问题标题】:How can I use BlobstoreUploadHandler with jQuery's post method如何将 Blob 存储 UploadHandler 与 jQuery post 方法一起使用
【发布时间】:2014-03-14 17:48:56
【问题描述】:

我正在尝试使用代码将文件上传到 GAE 的 BlobStore:

$(function() {
    $("input[type=file]").button().change(function( event ) {
    var file = document.getElementById('file_load').files[0];
    var reader = new FileReader();
    reader.readAsText(file, 'UTF-8');
    reader.onload = shipOff;
    });
});
function shipOff(event) {
    var result = event.target.result;
    var fileName = document.getElementById('file_load').files[0].name;
    $.post('{{ upload_url }}', { data: result, name: fileName}, afterSubmission);
}

但是,blobstoreUploadHandler 不会读取此内容:

class Upload(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        upload_files = self.get_uploads()
        blob_info = upload_files[0]

导致:

blob_info = upload_files[0]
IndexError: list index out of range

使用 webapp2 的处理程序,相同的 javascript 代码运行良好。

【问题讨论】:

  • 您必须发布多部分表单。使用 FormData()
  • 好的,我将代码更改为: function shipOff(event) { var fd = new FormData(); fd.append('文件', event.target.result); $.ajax({ url: '{{ upload_url }}', data: fd, processData: false, contentType: false, type: 'POST', 成功: afterSubmission }); } 虽然在服务器端仍然存在同样的问题,但现在内容类型是“multipart/form-data”
  • 看看这个 gcs_upload 处理程序,因为你可以用这段代码检查发生了什么。它不使用 blob_store 服务 url。您可以先使用表单进行测试,然后再使用您的 ajax 代码进行测试。 gist.github.com/voscausa/9541133

标签: javascript jquery python google-app-engine


【解决方案1】:

尝试将文件字段的name 属性传递给get_uploads 方法,如下所示:

HTML

<input type="file" name="file">

Python

... = get_uploads('file')

另一种可能性是您没有创建上传成功所需的blob-key。用我自己的 cmets 形成get_upload 方法:

def get_uploads(self, field_name=None):
    """Get uploads sent to this handler.

    Args:
      field_name: Only select uploads that were sent as a specific field.

    Returns:
      A list of BlobInfo records corresponding to each upload.
      Empty list if there are no blob-info records for field_name.
    """
    if self.__uploads is None:
      self.__uploads = collections.defaultdict(list)
      for key, value in self.request.params.items():
        if isinstance(value, cgi.FieldStorage):
          if 'blob-key' in value.type_options: # __uploads field is updated if blob-key is present
            self.__uploads[key].append(blobstore.parse_blob_info(value))

    if field_name:
      return list(self.__uploads.get(field_name, []))
    else:
      results = [] # if not __uploads and not field_name returns [], this is what happened to you
      for uploads in self.__uploads.itervalues():
        results.extend(uploads)
      return results

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 2020-07-13
    • 2016-05-15
    • 1970-01-01
    • 2014-11-26
    • 2011-06-18
    相关资源
    最近更新 更多