Flask implement upload and download function

Source: Internet
Author: User

#!-*-coding=utf-8-*-#From flask Import Flask##app = Flask (__name__)###@app. Route ('/')#def hello_world ():#return ' Hello world! '###if __name__ = = ' __main__ ':#App.run () fromWerkzeug.utilsImportSecure_filename fromFlaskImportflask,render_template,jsonify,request,send_from_directoryImport TimeImportOSImportBase64app= Flask (__name__) Upload_folder='Upload'app.config['Upload_folder'] =Upload_folderbasedir= Os.path.abspath (Os.path.dirname (__file__)) Allowed_extensions= Set (['txt','PNG','jpg','xls','JPG','PNG','xlsx','gif','GIF'])#used to determine the file suffixdefallowed_file (filename):return '.' inchFileName andFilename.rsplit ('.', 1) [1]inchallowed_extensions#for Test uploads, later@app. Route ('/test/from')defupload_test ():returnRender_template ('from.html')#Uploading Files@app. Route ('/api/upload', methods=['POST'],strict_slashes=False)defapi_upload (): File_dir= Os.path.join (Basedir, app.config['Upload_folder'])    if  notos.path.exists (File_dir): Os.makedirs (file_dir) F= request.files['myfile']#gets the file from the form's file field, myfile the form's name value    ifF andAllowed_file (F.filename):#determine if the file type is allowed to be uploadedFName =secure_filename (f.filename)Printfname ext= Fname.rsplit ('.', 1) [1]#get file suffixUnix_time =Int (time.time ())#new_filename = str (unix_time) + '. ' +ext # modified the file name of the uploadNew_filename =' A'+'.'+ext#modified the file name of the uploadF.save (Os.path.join (file_dir,new_filename))#Save the file to the upload directorytoken =Base64.b64encode (new_filename)PrinttokenreturnJsonify ({"errno"70A"errmsg":"Upload Successful","token": Token}) Else:        returnJsonify ({"errno": 1001,"errmsg":"Upload failed"}) @app. Route ('/api/load', methods=['GET'])defload ():ifRequest.method = ="GET":        ifOs.path.isfile (Os.path.join ('Upload','12.jpg')):            returnSend_from_directory ('Upload','12.jpg', as_attachment=True)#abort (404)if __name__=='__main__': App.run (Debug=true, port=9999)

Official website: http://docs.jinkan.org/docs/flask/patterns/fileuploads.html

Flask implement upload and download function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.