#!-*-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