Flask 实现文件上传和下载(简单但实用)

这篇博客展示了如何利用Python的Flask框架创建一个简单的文件上传和下载应用。用户可以通过网页上传文件,文件会被保存到服务器的指定目录,并在上传成功后自动触发下载。代码包括了HTML模板和Flask应用程序的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录结构和代码 

root@master ~/w/upload# ll
total 4.0K
drwxr-xr-x. 3 root root  21 Jul  2 17:32 static/
drwxr-xr-x. 2 root root  25 Jul  5 17:40 templates/
-rw-r--r--. 1 root root 819 Jul  5 09:55 upload.py


root@master ~/workspace# tree upload/
upload/
|-- static
|   `-- uploads
|-- templates
|   `-- upload.html
`-- upload.py

3 directories, 2 files

upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>upload:</h1>
    <form action="" enctype='multipart/form-data' method='POST'>
        <input type="file" name="file">
        <input type="submit" value="upload">
    </form>
</body>
</html>

upload.py

# coding:utf-8

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

app = Flask(__name__)

@app.route('/upload', methods=['POST', 'GET'])
def upload():
    if request.method == 'POST':
        f = request.files['file']
        basepath = os.path.dirname(__file__)
        upload_path = os.path.join(basepath, 'static/uploads', f.filename)
        f.save(upload_path)
        print('uploading ...')
    return render_template('upload.html')

@app.route('/download')
def download():
    dir_path = "/root/"
    filename = "test.sh"
    print('downloading ...')
    return send_from_directory(dir_path, filename, as_attachment=True)


if __name__ == '__main__':
    app.run(host="0.0.0.0", debug=True)

上传和下载测试 

启动服务(默认端口是 5000):

root@master ~/w/upload# python3 upload.py
 * Serving Flask app "upload" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 332-961-513

选择上传文件(如果页面打不开,可以先用 systemctl stop firewalld 命令关闭防火墙或者开放指定端口):

点击上传(上传后自动下载了测试文件 test.sh): 

上传成功:

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值