Python-FLASK上传文件

一、HTML文件

1、avator.html

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" action="upload">
    <input type="file" name="avator" id="avator" />
    <input type="submit" name="save" id="save" />
</form>
</body>
</html>

1、upload.html

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传成功</title>
</head>
文件名:{{ myfile }}
<p>你的头像上传成功!</p>
<img width="80px" src="/static/image/{{ myfile }}" />
</body>
</html>

二、上传文件
  1. file = request.files['avator']

    • request.files 是一个特殊的字典对象,用于存储通过HTTP请求上传到Flask应用程序的文件。
    • 'avator' 是请求中表单字段的名称。在HTML表单中,有一个这样的文件输入:<input type="file" name="avator">。这里的name属性值就是'avator'
    • request.files['avator'] 返回一个Werkzeug的FileStorage对象,该对象表示用户上传的文件。这个对象包含了文件的内容及其相关信息,比如文件名。
  2. file.save(...):

    • file 变量此时是一个FileStorage对象,包含了上传文件的所有信息。
    • file.save(...)FileStorage对象的方法,用于将上传的文件保存到服务器的文件系统中。save()方法的参数是你希望文件被保存在服务器上的路径。

因此,在这两行代码中,file是一个变量名,用于引用FileStorage对象。file承载了上传的文件数据,并提供了一些方法(如save)用于处理文件,比如将其保存到磁盘。

复制代码
@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['avator']
    myfilename=file.filename
    file.save('static/image/'+myfilename)
    return render_template('upload.html', myfile=myfilename)

还可以这样写:

@app.route('/upload', methods=['POST'])

def upload():

file = request.files['file']

file_name = file.filename

file_path = os.path.join('path/to/save/file/', file_name)

file.save(file_path)

return render_template('upload.html', myfile=myfilename)

相关推荐
databook10 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室10 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三12 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户25191624271115 小时前
Python之语言特点
python
刘立军15 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机19 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机20 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i21 小时前
django中的FBV 和 CBV
python·django
c8i21 小时前
python中的闭包和装饰器
python
这里有鱼汤1 天前
小白必看:QMT里的miniQMT入门教程
后端·python