Search code examples
javascriptjquerypythongoogle-app-engineblobstore

Generate upload url before form submission


I am trying to resolve expired upload urls by delaying their generation before a file uploads and not when the form is rendered. A solution I found is to do this on form submission or on button click events like so:

$('#btn-upload').click(function(event){
  event.preventDefault();

  var uploadUrl = '';
  $.get( "/generate_upload_url", function(data) {
    uploadUrl = data;
  });

  $('#my-form').attr('action', uploadUrl);
});

And on the serverside I have a Handler that generates upload urls like so:

class GenerateUploadUrlHandler(BaseHandler):
    def get(self):
        upload_url = blobstore.create_upload_url('/upload')
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write(upload_url)

I would expect when I click the button to generate new upload url and make a POST request there, but what happens is the form's action is filled with a delay and the POST request is done to a wrong URL. I suspect this might be because I'm doing async GET request and my form is submitted at the same time, but I'm not exactly sure as I see similar examples here: http://blog.notdot.net/2010/04/Implementing-a-dropbox-service-with-the-Blobstore-API-part-3-Multiple-upload-support


Solution

  • Two things to try:

    1) put your $('#my-form').attr('action', uploadUrl); inside the $.get()' success callback above.

    2) if that doesn't work, switch from $.get() to $.ajax(), and set async to false.