When uploading data to Python flask.

Asked 2 years ago, Updated 2 years ago, 84 views

I understood that when you press submit in that code, http://localhost:5000/fileUpload is connected by the action...

upload.html

<html>
   <body>
      <form action = "http://localhost:5000/fileUpload" method = "POST"
         enctype = "multipart/form-data">
         <input type = "file" name = "file" />
         <input type = "submit"/>
      </form>
   </body>
</html>

I only made upload.html file, but I didn't make an html file called fileUpload, but it was possible to send it. I'd like to know how it can be transferred. I know that @app.route('/') is the part that receives from the local address, and that return sends the value. I'm confused. I'd appreciate your help.

flask_upload.py

from flask import Flask, render_template, request
from werkzeug import secure_filename
app = Flask(__name__)

#Rendering upload HTML
@app.route('/upload')
def render_file():
   return render_template('upload.html')

#Process file upload
@app.route('/fileUpload', methods = ['GET', 'POST'])
def upload_file():
   if request.method == 'POST':
      f = request.files['file']
      #Path to save + filename
      f.save(secure_filename(f.filename))
      return 'uploads directory -> File upload succeeded!'

if __name__ == '__main__':
    #Run Server
   app.run(debug = True)

python flask

2022-09-22 16:21

1 Answers

I didn't even create an html file called ~, but I implemented routing to make it possible.

Routing is the process of selecting a path to send communication data within a network. Wikiback

# Flask: "Ah! If people access http://localhost/upload, where do they send it to?
@app.route('/upload')

# I should let this function handle such HTTP requests!"
def render_file():

    # Function: "Yes, well. I can just use the upload.html file template and draw the screen and return it."
    return render_template('upload.html')

# Flask: "Huck, but when people access through http://localhost/fileUpload, where else should I send it?
@app.route('/fileUpload', methods = ['GET', 'POST'])

# That HTTP request should be done by this function!"
def upload_file():

    # Function: "Oh really? Then, when the method of the HTTP request happens to be POST,
    if request.method == 'POST':

        # Maybe there's some data assigned to "file" in the file upload part of the request
        f = request.files['file']

        # I'll save it with the appropriate file name
        f.save(secure_filename(f.filename))

        # I will return the notification message and end."
        return 'uploads directory -> File upload succeeded!'

For more accurate commentary, read official document .


2022-09-22 16:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.