简体   繁体   中英

How can I use BlobstoreUploadHandler with jQuery's post method

I'm trying to upload a file to GAE's BlobStore using the code:

$(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);
}

this however is not read by the blobstoreUploadHandler:

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

resulting in:

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

The same javascript code worked fine using webapp2's handler.

Try passing the name property of the file field to the get_uploads method like this:

HTML

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

Python

... = get_uploads('file')

The other possibility is that you didn't create the blob-key which is required for the upload to succeed. Form the get_upload method with my own comments:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM