概述
但我不知道如何上传文件夹或一些文件.我搜索过,我发现了这个:
Uploading multiple files with Flask.最后,我得到了如何上传多文件上传.
我会告诉你下面的代码:(这是一个好习惯吗?我不知道)
@app.route('/upload/',methods = ['GET','POST']) def upload_file(): if request.method =='POST': files = request.files.getlist('file[]',None) if files: for file in files: filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename)) return hello() return render_template('file_upload.html')
但是,我仍然不知道如何上传属于该文件夹的文件夹和文件.
你能告诉我怎么样?
我正在处理的目录树:
. ├── manage.py ├── templates │ ├── file_upload.html │ └── hello.html └── uploads ├── BX6dKK7CUAAakzh.jpg └── sample.txt
from flask import Flask,abort,render_template,request,redirect,url_for from werkzeug import secure_filename import os app = Flask(__name__) UPLOAD_FOLDER = './uploads' app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER @app.route('/') def index(): return redirect(url_for('hello')) @app.route('/hello/') @app.route('/hello/<name>') def hello(name = None): return render_template('hello.html',name=name) @app.route('/upload/','POST']) def upload_file(): if request.method =='POST': file = request.files['file'] if file: filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename)) return hello() return render_template('file_upload.html') if __name__ == '__main__': app.run(debug = True)
<!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='file[]' multiple=''> <input type='submit' value='upload'> </p> </form>
UPLOAD_FOLDER = './uploads'
flask找不到此目录并返回500错误.
如果你把它改为:
UPLOAD_FOLDER = '/tmp'
您需要编辑正确目录的路径,以便正确上载文件.
总结
以上是编程之家为你收集整理的python – 使用Flask上传文件夹/文件全部内容,希望文章能够帮你解决python – 使用Flask上传文件夹/文件所遇到的程序开发问题。
如果您也喜欢它,动动您的小指点个赞吧