项目实训(八):用flask实现文件的上传与下载

本文介绍了如何在Flask项目中实现文件上传和下载功能,为后续算法集成提供基础接口。通过POST请求上传用户选择的文件,读取内容并在指定位置生成新的文本文件。GET请求则用于下载处理过的文件,同时处理可能的异常情况。

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

我们在项目实训(七)中已经完成了简单的flask应用,但是项目需要一个能够实现功能的接口,因为算法部分还没有确定下来,所以要先实现上传文件和下载文件这俩功能,后期再将算法部分嵌入进去。本篇的代码要和基础结构结合起来看哦~

@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',secure_filename(f.filename))  #注意:没有的文件夹一定要先创建,不然会提示没有该路径
        f.save(upload_path)

        with open("static/uploads/"+f.filename, "r") as f:  # 打开文件
            data = f.read()  # 读取文件
            print(data)

        #print(f.name)
        #print(0)

        text_create('log.txt',data)
        return redirect(url_for('upload'))
    return render_template('upload.html')

当用户进入/upload这个url时,需要手动选择上传一个文件(这了有一个简单的UI,写在upload.html中),之后程序会将上传的文件存放在服务器计算机指定的位置。之后这个程序会在打开这个保存下来的文件并读取其中的内容。(这里只设定了简单的txt文件)随后会使用text_create函数在指定位置生成另一个txt文件,在对源文件内容进行加工后写入。

网页示例:

@app.route('/download', methods=['POST', 'GET'])
def download():
    if request.method == 'GET':
        print(1)
        directory = './processed/'
        try:
            response = make_response(
                send_from_directory(directory, 'log.txt', as_attachment=True))
            return response
        except Exception as e:
            return jsonify({"code": "异常", "message": "{}".format(e)})
    return render_template('upload.html')

/download与上面的逻辑相仿:得到get参数之后,就会去往我们储存处理过文本的地方,然后把这个文本作为一个response传回去,这里还加了一个异常报错。

 此处是text_create函数:

def text_create(name, msg):
    desktop_path = "./processed/"  # 新创建的txt文件的存放路径
    full_path = desktop_path + name # 也可以创建一个.doc的word文档
    file = open(full_path, 'w')
    file.write(msg)
    file.write('---processed')
    # file.close()

此处是upload.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>文件上传示例</h1>
    <form action="" enctype='multipart/form-data' method='POST'>
        <input type="file" name="file">
        <input type="submit" value="上传">
    </form>
</body>
</html>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值