如何将BlobstoreUploadHandler与jQuery的post方法一起使用

时间:2014-03-14 17:48:57

标签: javascript jquery python google-app-engine

我正在尝试使用以下代码将文件上传到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代码工作正常。

1 个答案:

答案 0 :(得分:0)

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

HTML

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

的Python

... = get_uploads('file')

另一种可能性是您没有创建上传成功所需的blob-key。用我自己的评论形成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
相关问题