Flask:web中添加 upload file and download file 功能

这篇博客介绍了如何在Flask应用中实现文件上传和下载功能。通过在HTML表单中添加file字段,结合Flask的request.files获取上传文件,并提供安全的保存方法来避免恶意文件名。同时,讲解了处理文件缺失情况的代码以及提供了完整的app.py和相关模板文件。

在form表单中添加file;

            <form action={{url_for('download')}} method='POST' enctype="multipart/form-data">
                <input type="file" name='file'> <br>
                <button type="submit">Submit</button>
            </form>

app.py中使用request.files()得到file;
别忘了method=[“POST”];

from flask import Flask,render_template,request,send_file         #得到email by request

app=Flask(__name__)

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

@app.route('/download', methods=['POST'])
def download():
    if request.method=='POST':
        file=request.files["file"]  #input里的file name
        print(file.read())
        print(file)  #<FileStorage: 'Sample.csv' ('application/vnd.ms-excel')>
        print(type(file))  #<class 'werkzeug.datastructures.FileStorage'>
        return render_template('home.html')

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

添加save功能:

@app.route('/download', methods=['POST'])
def download():
    if request.method=='POST':
        file=request.files["file"]  #input里的file name
        file.save("uploaded"+file.filename)  #储存在上传的文件的目录下
        print(file.read())
        print(file)  #<FileStorage: 'Sample.csv' ('application/vnd.ms-excel')>
        print(type(file))  #<class 'werkzeug.datastructures.FileStorage'>
        return render_template('home.html')

防止含攻击代码的文件名

from werkzeug.utils import secure_filename

@app.route('/submit', methods=['POST'])
def submit():
    if request.method=='POST':
        file=request.files["file"]  #input里的file name
        #file.save(secure_filename("uploaded"+file.filename))  #防止含攻击代码的文件名
        with open("uploaded"+file.filename,"a") as f:
            f.write("This is an add words!")
        return render_template('home.html',btn="download.html")

home.html
ignore missing 当缺失此类时,忽略此代码;

<!DOCTYPE html>
<html>
    <title>Super GeoCoder</title>
    <head>
        <link href='../static/main.css' rel="stylesheet">
    </head>
    <body>
        <div class="container">
            <h1>Super GeoCoder</h1>
            <h3>Upload your <span>CSV file</span> to get the longitude and latitude of your Address!</h3>
            <p>Make sure that you have an <span>Address column</span> in your CSV file</p>
            <form action={{url_for('submit')}} method='POST' enctype="multipart/form-data">
                <input type="file" name='file'> <br>
                <button type="submit">Submit</button>
            </form>
            {% include [btn] ignore missing %}   
        </div>
    </body>
</html>

完整代码

app.py

from flask import Flask,render_template,request,send_file         #得到email by request
#from werkzeug import secure_filename
from werkzeug.utils import secure_filename

app=Flask(__name__)

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

@app.route('/submit', methods=['POST'])
def submit():
    global file
    if request.method=='POST':
        file=request.files["file"]  #input里的file name
        file.save(secure_filename("uploaded"+file.filename))  #防止含攻击代码的文件名
        with open("uploaded"+file.filename,"a") as f:
            f.write("This is an add words!")
        return render_template('home.html',btn="download.html")

@app.route('/download')
def download():
    return send_file("upload"+file.filename, attachment_filename="Your file",as_attachment=True)  #file需要设为全局变量

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

home.html

<!DOCTYPE html>
<html>
    <title>Super GeoCoder</title>
    <head>
        <link href='../static/main.css' rel="stylesheet">
    </head>
    <body>
        <div class="container">
            <h1>Super GeoCoder</h1>
            <h3>Upload your <span>CSV file</span> to get the longitude and latitude of your Address!</h3>
            <p>Make sure that you have an <span>Address column</span> in your CSV file</p>
            <form action={{url_for('submit')}} method='POST' enctype="multipart/form-data">
                <input type="file" name='file'> <br>
                <button type="submit">Submit</button>
            </form>
            {% include [btn] ignore missing %}  
        </div>
    </body>
</html>

download.html

<!DOCTYPE html>
<html lang="en">
    <div class="container">
        <a href={{url_for('download')}} target="blank"><button class='btn'>download</button> </a>
    </div>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值