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)

相关推荐
ㄟ留恋さ寂寞9 小时前
Golang怎么限制请求Body大小_Golang如何防止客户端发送过大的请求体【避坑】
jvm·数据库·python
Chase_______9 小时前
【Java杂项】0.1 + 0.2 为什么不等于 0.3?IEEE 754 与 BigDecimal 精度避坑
java·开发语言·python
风之所往_9 小时前
Python 3.2 新特性全面总结
python
ch.ju9 小时前
Java Programming Chapter 4——Static part
java·开发语言
geovindu9 小时前
python: Monitor Pattern
开发语言·python·设计模式·监控模式
Naisu Xu9 小时前
Mac上安装Homebrew、Git、Python等环境记录
git·python·macos·终端·brew
之歆9 小时前
DAY_11JavaScript BOM与DOM深度解析:底层原理与工程实践(上)
开发语言·前端·javascript·ecmascript
老纪9 小时前
CSS Flex布局中如何实现导航栏与Logo的左右分布_利用justify-content- space-between
jvm·数据库·python
会编程的土豆9 小时前
Go ini 配置加载:`ini.MapTo` 详细解析
开发语言·数据库·golang
ChoSeitaku9 小时前
04.数组
java·开发语言·数据结构