Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to receive uploaded file with Klein like Flask in python

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?

like image 698
JLTChiu Avatar asked Aug 24 '16 19:08

JLTChiu


People also ask

How do I access my uploaded files on flask?

Python for web development using Flask Handling file upload in Flask is very easy. It needs an HTML form with its enctype attribute set to 'multipart/form-data', posting the file to a URL. The URL handler fetches file from request. files[] object and saves it to the desired location.

How do I get the full path of an uploaded file in Python?

To get current file's full path, you can use the os. path. abspath function. If you want only the directory path, you can call os.

How will you upload a file on to the Web server explain with example in Python?

An enctype attribute called multi-part/form-data is required in a HTML form to upload a file. Secondly we will be required to use the input tag of HTML and set it equal to “file”. This adds a upload button in addition to an input button in the form.

How do you make a upload button in Python?

Method 1: Using the Python's os Module: Also, the enctype attribute with "multi-part/form-data" value will help the HTML form to upload a file. Lastly, we need the input tag with the filename attribute to upload the file we want. Lastly, we need the input tag with the filename attribute to upload the file we want.


1 Answers

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.

like image 172
notorious.no Avatar answered Oct 14 '22 08:10

notorious.no