当前位置:   article > 正文

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

python开发网页上传文件

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 '文件已上传'

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

在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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

main.py

import os

from flask import Flask, request, render_template

app = 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()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

演示

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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/酷酷是懒虫/article/detail/768103
推荐阅读
相关标签
  

闽ICP备14008679号