IT TIP

Google App Engine에서 파일 업로드

itqueen 2020. 10. 14. 21:29
반응형

Google App Engine에서 파일 업로드


사용자가 Visual Studio 프로젝트 파일을 다운 그레이드 할 수있는 웹 앱을 만들 계획입니다. 그러나, 구글 앱 엔진은 파일 업로드 및 통해 구글 서버에 저장하는 플랫 파일 받아들이는 것 db.TextProperty등을 db.BlobProperty.

이 작업을 수행 할 수있는 방법에 대한 코드 샘플 (클라이언트 및 서버 측 모두)을 누구든지 제공 할 수있어 기쁩니다.


여기에 완전한 작업 파일이 있습니다. Google 사이트에서 원본을 가져 와서 좀 더 현실적으로 만들도록 수정했습니다.

주의해야 할 몇 가지 사항 :

  1. 이 코드는 BlobStore API를 사용합니다.
  2. ServeHandler 클래스에서이 줄의 목적은 키를 "고정"하여 브라우저에서 발생할 수있는 모든 이름 변경을 제거하는 것입니다 (Chrome에서는 관찰되지 않음).

    blob_key = str(urllib.unquote(blob_key))
    
  3. 이 끝에있는 "save_as"절이 중요합니다. 파일 이름이 브라우저로 전송 될 때 왜곡되지 않도록합니다. 무슨 일이 일어나는지 관찰하기 위해 그것을 제거하십시오.

    self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True)
    

행운을 빕니다!

import os
import urllib

from google.appengine.ext import blobstore
from google.appengine.ext import webapp
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

class MainHandler(webapp.RequestHandler):
    def get(self):
        upload_url = blobstore.create_upload_url('/upload')
        self.response.out.write('<html><body>')
        self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
        self.response.out.write("""Upload File: <input type="file" name="file"><br> <input type="submit" name="submit" value="Submit"> </form></body></html>""")

        for b in blobstore.BlobInfo.all():
            self.response.out.write('<li><a href="/serve/%s' % str(b.key()) + '">' + str(b.filename) + '</a>')

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        upload_files = self.get_uploads('file')
        blob_info = upload_files[0]
        self.redirect('/')

class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, blob_key):
        blob_key = str(urllib.unquote(blob_key))
        if not blobstore.get(blob_key):
            self.error(404)
        else:
            self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True)

def main():
    application = webapp.WSGIApplication(
          [('/', MainHandler),
           ('/upload', UploadHandler),
           ('/serve/([^/]+)?', ServeHandler),
          ], debug=True)
    run_wsgi_app(application)

if __name__ == '__main__':
  main()

실제로이 질문은 App Egnine 문서에 답변되어 있습니다. 사용자 이미지 업로드에 대한 예를 참조하십시오 .

<form> </ form> 내부의 HTML 코드 :

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

Python 코드 :

class Guestbook (webapp.RequestHandler) :
  def post (self) :
    greeting = 인사말 ()
    users.get_current_user () :
      greeting.author = users.get_current_user ()
    greeting.content = self.request.get ( "content")
    avatar = self.request.get ( "img")
    greeting.avatar = db.Blob (아바타)
    greeting.put ()
    self.redirect ( '/')

There is a thread in Google Groups about it:

Uploading Files

With a lot of useful code, that discussion helped me very much in uploading files.


Google has released a service for storing large files. Have a look at blobstore API documentation. If your files are > 1MB, you should use it.


I try it today, It works as following:

my sdk version is 1.3.x

html page:

<form enctype="multipart/form-data" action="/upload" method="post" > 
<input type="file" name="myfile" /> 
<input type="submit" /> 
</form> 

Server Code:

file_contents = self.request.POST.get('myfile').file.read() 

If your still having a problem, check you are using enctype in the form tag

No:

<form encoding="multipart/form-data" action="/upload">

Yes:

<form enctype="multipart/form-data" action="/upload">

You can not store files as there is not a traditional file system. You can only store them in their own DataStore (in a field defined as a BlobProperty)

There is an example in the previous link:

class MyModel(db.Model):
  blob = db.BlobProperty()

obj = MyModel()
obj.blob = db.Blob( file_contents )

Personally I found the tutorial described here useful when using the Java run time with GAE. For some reason, when I tried to upload a file using

<form action="/testservelet" method="get" enctype="multipart/form-data">
    <div>
        Myfile:<input type="file" name="file" size="50"/>
    </div>

    <div>
        <input type="submit" value="Upload file">
    </div>
</form>

I found that my HttpServlet class for some reason wouldn't accept the form with the 'enctype' attribute. Removing it works, however, this means I can't upload any files.


There's no flat file storing in Google App Engine. Everything has to go in to the Datastore which is a bit like a relational database but not quite.

You could store the files as TextProperty or BlobProperty attributes.

There is a 1MB limit on DataStore entries which may or may not be a problem.


I have observed some strange behavior when uploading files on App Engine. When you submit the following form:

<form method="post" action="/upload" enctype="multipart/form-data">
    <input type="file" name="img" />
    ...
</form>

And then you extract the img from the request like this:

img_contents = self.request.get('img')

The img_contents variable is a str() in Google Chrome, but it's unicode in Firefox. And as you now, the db.Blob() constructor takes a string and will throw an error if you pass in a unicode string.

Does anyone know how this can be fixed?

Also, what I find absolutely strange is that when I copy and paste the Guestbook application (with avatars), it works perfectly. I do everything exactly the same way in my code, but it just won't work. I'm very close to pulling my hair out.


There is a way of using flat file system( Atleast in usage perspective)

There is this Google App Engine Virtual FileSystem project. that is implemented with the help of datastore and memcache APIs to emulate an ordinary filesystem. Using this library you can use in you project a similar filesystem access(read and write).

참고URL : https://stackoverflow.com/questions/81451/upload-files-in-google-app-engine

반응형