问题描述:

I'm using flask to develop webapp and I have two different files to upload to two different locations and as far as I search through the internet I only find explanation to upload one or multiple together in one file field and it works fine.

here is the code i used to upload one file:

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):

return '.' in filename and \

filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route("/", methods=['GET', 'POST'])

def index():

if request.method == 'POST':

file = request.files['file']

if file > 0:

filename = secure_filename(file.filename)

file.save(os.path.join(UPLOAD_FOLDER , filename))

return redirect(url_for('index'))

can someone help me with that

网友答案:

The name of the input will be the key which you retrieve the file from request.files

html:

<input type="file" name="first_file" />
<input type="file" name="second_file" />

Flask:

@app.route("/", methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        first_file = request.files['first_file']
        second_file = request.files['second_file']
        ... # do stuff with files

Documentation.

网友答案:

here is the whole code:

import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename
import sys
sys.path.insert(0, '/home/muteb/Desktop/test')

UPLOAD_FOLDER = '/home/muteb/Desktop/test/'


app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


@app.route("/", methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        file1 = request.files['file1']
        file2 = request.files['file2']
        if file1 > 0:
            filename1 = secure_filename(file1.filename)
            file1.save(os.path.join(UPLOAD_FOLDER , filename1))
        if file2 > 0:
            filename2 = secure_filename(file2.filename)
            file2.save(os.path.join(UPLOAD_FOLDER , filename2))
            return redirect(url_for('index'))
    return """
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form action="" method=post enctype=multipart/form-data>
      <p><input type=file name=file1>
          <input type=file name=file2>
         <input type=submit value=Upload>
    </form>
    <p>%s</p>
    """ % "<br>".join(os.listdir(app.config['UPLOAD_FOLDER'],))

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5002, debug=True)
相关阅读:
Top