当前位置:首页 » 《我的小黑屋》 » 正文

python Flask 写一个简易的 web 端上传文件程序 (附demo)

6 人参与  2024年03月30日 14:15  分类 : 《我的小黑屋》  评论

点击全文阅读


python Flask 写一个简易的 web 端上传文件程序 (附demo)

需求介绍核心代码: 文件结构前端文件后端文件 完整代码演示


需求

在当今数字化时代,文件上传需求日益普遍。无论是个人还是企业,都可能需要实现文件上传功能。为此,本文将分享如何使用Python Flask框架创建一个简易的Web端上传文件程序。

介绍

需要源码的留下邮箱,私信也会看,不过看的不勤,留言有通知。

Flask 是一个用于构建 Web 应用程序的轻量级 Python Web 框架。它设计简单、易于学习和使用,但同时也非常灵活,适用于从小型项目到大型应用程序的各种场景。

核心代码:

@app.route('/upload', methods=['POST'])def upload_file():    if 'file' not in request.files:        return '无文件部分'    file = request.files['file']    if file.filename == '':        return '没有可选择的文件'    if file:        # 设置文件存储路径        upload_path = os.path.join('static/uploads', file.filename)        # 检测路径是否存在,不存在则创建        if not os.path.exists(os.path.dirname(upload_path)):            os.makedirs(os.path.dirname(upload_path))        # 存储文件        file.save(upload_path)        return '文件已上传'

在Flask中,request.files 是用于处理上传文件的对象。当用户通过表单上传文件时,这个对象可以用来访问和处理上传的文件数据。request.files 是一个字典,其中键是表单中文件上传字段的名称,值是与该字段相关联的文件对象。

request.files 字典中文件对象常见的字段和方法:

字段/方法描述示例
filename获取上传文件的原始文件名filename = request.files[‘file’].filename
stream获取文件的二进制流,可用于读取文件内容file_content = request.files[‘file’].stream.read()
content_type获取文件的MIME类型。content_type = request.files[‘file’].content_type
content_length获取文件的内容长度(以字节为单位)content_length = request.files[‘file’].content_length
save(destination)将上传的文件保存到指定的目标路径destination是保存文件的路径,可以是相对路径或绝对路径request.files[‘file’].save(‘uploads/’ + filename)

file.save() 是用于将上传的文件保存到指定的目标路径。

文件结构

下面我们介绍一下我们的文件结构

在这里插入图片描述

前端文件

templates.index.html

后端文件

main.py

完整代码

index.html

<!DOCTYPE html><html><head>    <meta charset="utf-8">    <meta name="viewport" content="width=device-width, initial-scale=1">    <title>文件工作台</title></head><body><h1>文件工作台</h1><form>    <input type="file" id="file" name="file">    <button type="button" onclick="uploadFile()">上传文件</button></form></body></html><script>    function uploadFile() {        var fileInput = document.getElementById('file');        var file = fileInput.files[0];        if (file) {            var formData = new FormData();            formData.append('file', file);            var xhr = new XMLHttpRequest();            xhr.open('POST', '/upload', true);            xhr.onload = function () {                if (xhr.status == 200) {                    alert('文件上传成功');                } else {                    alert('文件上传失败');                }            };            xhr.send(formData);        } else {            alert('请选择一个文件');        }    }</script>

main.py

import osfrom flask import Flask, request, render_templateapp = Flask(__name__)@app.route('/')def index():    return render_template('index.html')@app.route('/upload', methods=['POST'])def upload_file():    if 'file' not in request.files:        return '无文件部分'    file = request.files['file']    if file.filename == '':        return '没有可选择的文件'    if file:        # 设置文件存储路径        upload_path = os.path.join('static/uploads', file.filename)        # 检测路径是否存在,不存在则创建        if not os.path.exists(os.path.dirname(upload_path)):            os.makedirs(os.path.dirname(upload_path))        # 存储文件        file.save(upload_path)        return '文件已上传'if __name__ == '__main__':    app.run()

演示

在这里插入图片描述
在这里插入图片描述

需要源码的留下邮箱,私信也会看,不过看的不勤,留言有通知。


点击全文阅读


本文链接:http://zhangshiyu.com/post/88140.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1