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’].filenamestream获取文件的二进制流,可用于读取文件内容file_content = request.files[‘file’].stream.read()content_type获取文件的MIME类型。content_type = request.files[‘file’].content_typecontent_length获取文件的内容长度(以字节为单位)content_length = request.files[‘file’].content_lengthsave(destination)将上传的文件保存到指定的目标路径destination是保存文件的路径,可以是相对路径或绝对路径request.files[‘file’].save(‘uploads/’ + filename)

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

文件结构

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

前端文件

templates.index.html

后端文件

main.py

完整代码

index.html

文件工作台

文件工作台

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

演示

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

文章链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: