How to receive uploaded file with Klein like Flask in python

余生长醉 提交于 2019-12-23 08:51:15

问题


When setting up a Flask server, we can try to receive the file user uploaded by

imagefile = flask.request.files['imagefile']
filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
    werkzeug.secure_filename(imagefile.filename)
filename = os.path.join(UPLOAD_FOLDER, filename_)
imagefile.save(filename)
logging.info('Saving to %s.', filename)
image = exifutil.open_oriented_im(filename)

When I am looking at the Klein documentation, I've seen http://klein.readthedocs.io/en/latest/examples/staticfiles.html, however this seems like providing file from the webservice instead of receiving a file that's been uploaded to the web service. If I want to let my Klein server able to receive an abc.jpg and save it in the file system, is there any documentation that can guide me towards that objective?


回答1:


As Liam Kelly commented, the snippets from this post should work. Using cgi.FieldStorage makes it possible to easily send file metadata without explicitly sending it. A Klein/Twisted approach would look something like this:

from cgi import FieldStorage
from klein import Klein
from werkzeug import secure_filename

app = Klein()

@app.route('/')
def formpage(request):
    return '''
    <form action="/images" enctype="multipart/form-data" method="post">
    <p>
        Please specify a file, or a set of files:<br>
        <input type="file" name="datafile" size="40">
    </p>
    <div>
        <input type="submit" value="Send">
    </div>
    </form>
    '''

@app.route('/images', methods=['POST'])
def processImages(request):
    method = request.method.decode('utf-8').upper()
    content_type = request.getHeader('content-type')

    img = FieldStorage(
        fp = request.content,
        headers = request.getAllHeaders(),
        environ = {'REQUEST_METHOD': method, 'CONTENT_TYPE': content_type})
    name = secure_filename(img[b'datafile'].filename)

    with open(name, 'wb') as fileOutput:
        # fileOutput.write(img['datafile'].value)
        fileOutput.write(request.args[b'datafile'][0])

app.run('localhost', 8000)

For whatever reason, my Python 3.4 (Ubuntu 14.04) version of cgi.FieldStorage doesn't return the correct results. I tested this on Python 2.7.11 and it works fine. With that being said, you could also collect the filename and other metadata on the frontend and send them in an ajax call to klein. This way you won't have to do too much processing on the backend (which is usually a good thing). Alternatively, you could figure out how to use the utilities provided by werkzeug. The functions werkzeug.secure_filename and request.files (ie. FileStorage) aren't particularly difficult to implement or recreate.



来源:https://stackoverflow.com/questions/39131368/how-to-receive-uploaded-file-with-klein-like-flask-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!