1

I have a server side code to process uploaded binary files:

class UploadHandler(webapp.RequestHandler):
    def post(self):
        file_name = files.blobstore.create(mime_type='application/octet-stream')
        with files.open(file_name, 'a') as f:
            f.write('data')
        files.finalize(file_name)
        blob_key = files.blobstore.get_blob_key(file_name)

It's the code from examples so actually it doesn't process any uploaded files, just create a new Blobstore entity and writes some data to this. From the client side I have this part of the code that actually sends the file to the server:

    var xhr = new XMLHttpRequest();
    xhr.open("post", "/upload", true);

    xhr.setRequestHeader("Content-Type", "multipart/form-data");
    xhr.setRequestHeader("X-File-Name", file.fileName);
    xhr.setRequestHeader("X-File-Size", file.fileSize);
    xhr.setRequestHeader("X-File-Type", file.type);

    xhr.send(file);

In FireBug I see it uploads the file to the server and the server code creates a file as it is supposed to be. The thing I can't figure out is how to connect these two parts so that server side code could receive the uploaded file as a stream. I don't use forms so I can't get the file with something like upload_files = self.get_uploads('file'). How do I retrieve the file on the server side?

UPDATE: I have found an answer in GAE documentation about webapp request handlers. I need to use something like this uploaded_file = self.request.body to get the file stream. Then I just use f.write(uploaded_file) to save it. It seems to work for me. Please share you thoughts if it's a good approach.

1 Answer 1

1

Should be something like this:

class UploadHandler(webapp.RequestHandler):
    def post(self):
        mime_type = self.request.headers['X-File-Type']
        name = self.request.headers['X-File-Name']
        file_name = files.blobstore.create(mime_type=mime_type,
                                           _blobinfo_uploaded_filename=name)
        with files.open(file_name, 'a') as f:
            f.write(self.request.body)
        files.finalize(file_name)
        blob_key = files.blobstore.get_blob_key(file_name)

Your custom headers and body can be pulled from the WebOb Request object. Note that you don't need to inherit from BlobStoreUploadHandler since you're not using an HTML upload form.

Sign up to request clarification or add additional context in comments.

1 Comment

This will only work if the file is less than 10MB. Otherwise, you should send a correctly encoded multipart form and use the regular blobstore upload method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.