existIntroduction to Flask Web Development (10) Picture upload (using Flask-Uploads)We've introduced the useFlaskThe plug-in Flask-Uploads uploads pictures, and this chapter continues to discuss this topic.
We know we canUPLOADS_DEFAULT_DESTParameters to specify the default path for file upload, if the path we specify isuploadFor directory, then the path to the file is:
upload/files/xxx
Notice,filesforUploadSetname parameter inxxxas file name
In the previous chapter, we said that the core method of Flask-Uploads to save files is:
uploaded_photos.save(file)
This method returns the actual saved file namefilename, After we complete the save file action, we callurlmethod:
(‘%s url is %s’ % (filename, uploaded_photos.url(filename)))
You can get the full access path of the website to upload the file, that is, we specifyUPLOADS_DEFAULT_URLParameters +files/xxx,Right now:
url is http://127.0.0.1:9000/files/
After the image is uploaded, we still need to view the image. Therefore, based on the above analysis, our presentation code is implemented as follows:
# show photo
@('/files/<string:filename>', methods=['GET'])
def show_photo(filename):
if == 'GET':
if filename is None:
pass
else:
('filename is %s' % filename)
image_data = open((UPLOAD_PATH, 'files/%s' % filename), "rb").read()
response = make_response(image_data)
['Content-Type'] = 'image/png'
return response
else:
pass
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
Source code reference:/ypmc/flask-sqlalchemy-web