开发者

How to receive an uploaded file to store it using Blobstore API

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开发者_StackOverflow社区 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜