This article is an example of Python using the flask framework to upload multiple files at the same time to share with you for your reference. Specifically as follows:
The following demo code comes with a detailed HTML page and Python code
Import OS # We ll render HTML templates and access data sent by POST # using the ' request ' object from flask. Redirect and Url_for # 'll be used to Redirect the user once the upload are done # and send_from_directory'll help us to Send/show on the # Browser the ' file that ' the user just uploaded from flask import flask, render_template, request, Redire CT, url_for, send_from_directory from Werkzeug import secure_filename # Initialize the flask application app = Flask (__nam E__) # This is the "path to" Upload directory app.config[' upload_folder '] = ' uploads/' # These are the extension of that we Are accepting to is uploaded app.config[' allowed_extensions ' = set ([' txt ', ' pdf ', ' png ', ' jpg ', ' jpeg ', ' gif ']) # for a Given file, return whether it ' a allowed type or not def allowed_file (filename): "Return". ' in filename and \ Fi Lename.rsplit ('. ', 1) [1] in app.config[' allowed_extensions '] # This route'll show a form to perform an AJAX request # JQ Uery is loaded to execute the request and update the # Value of the Operation @app. Route ('/') def index (): Return render_template (' index.html ') # route
'll process the file upload @app. Route ('/upload ', methods=[' POST ') def upload (): # Get the name of the uploaded files Uploaded_files = Request.files.getlist ("file[]") filenames = [] for file in Uploaded_files: # Check if the file is one of the allowed types/extensions if file and Allowed_file (file.filename): # Make the filename safe, remove Unsupported chars filename = Secure_filename (file.filename) # Move the file form the temporal folder to the U Pload # Folder We setup File.save (Os.path.join (app.config[' Upload_folder '],filename)) # Save the Filenam E into a list, we'll use it later filenames.append (filename) # Redirect The user to the Uploaded_file route, W
Hich # would basicaly show on the browser of the uploaded file # Load an HTML page with a link to each uploaded file Return Render_template (' upload.html ', filenames=filenames) # This route is expecting a parameter containing the name # of a file. Then It'll locate that file on the upload # directory and show it to the browser, so if the user uploads # an image, tha T image is going the upload @app. Route ('/uploads/<filename> ') def uploaded_file (filename): return Send_from_directory (app.config[' upload_folder '], filename) if __name__ = = ' __main__ ': App.run (host = "0.0.0.0", Port=int ("a"), Debug=true)
Index.html Code
Upload.html page:
I hope this article will help you with your Python programming.