简体   繁体   中英

How to handle direct file upload with GAE/python?

Client side (javascript) uploads the application with XMLHttpRequest :

  var req = new XMLHttpRequest();
  req.open('POST', my_app_url, false);
  req.setRequestHeader("Content-Length", req.length);
  req.sendAsBinary(req.binary);

I use datastore on the server side (not blobstore). How can I save uploaded file to the datastore? I've found that ServletFileUpload can be used with Java. But how to do the same with Python?

You should use self.request.body

class YourUploadHandler(webapp.RequestHandler):
    def post(self):
        your_binary_content = self.request.body

If you mean on the appengine side, you just have to have a blobproperty. So something like...

class SomeEntity(db.Model):
    file_data = db.BlobProperty()

class AddData(webapp.RequestHandler)
    def post(self):
        data = self.request.get("filedata")
        e = SomeEntity(file_data = db.Blob(data))
        e.put()

As a note, I'm not sure if the code you posted above to send the request is correct, but you can upload the file with a simple html form, something like this:

<form action="/url_to_adddata_handler/" method="post">
    <input type="file" name="filedata">
    <input type="submit" value="Submit">
</form>

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