【Flask】文件上传(设置大小和路径)

 新建python文件upload_py.py

from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
import os

app = Flask(__name__)
app.config['MAX_CONTENT_PATH'] = 1024*1024 #指定最大文件大小,单位为字节


@app.route('/upload')
def upload_file():
    return render_template('upload.html')


@app.route('/uploader', methods=['GET', 'POST'])
def upload_file1():
    if request.method == 'POST':
        f = request.files['file']
        basepath = os.path.dirname(__file__)  # 当前文件所在路径
        print(basepath)
        upload_path = os.path.join(basepath, 'file', secure_filename(f.filename))
        # 注意:没有的文件夹一定要先创建,不然会提示没有该路径
        print(upload_path)
        upload_path = os.path.abspath(upload_path)  # 将路径转换为绝对路径
        print(upload_path)
        f.save(upload_path)
        return 'file uploaded successfully'
    return render_template('upload.html')


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

在py文件同级目录下新建templates/upload.html

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

猜你喜欢

转载自blog.csdn.net/u013066730/article/details/108367975