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)

相关推荐
李妍.2 小时前
02Numpy基础(上)
开发语言·python
TheBestRucy2 小时前
Python 九阳神功之贰:面向对象(下)
开发语言·python
2601_965958462 小时前
口腔黏膜脱皮超2周未愈建议及时就医
人工智能·python
AI_小站2 小时前
刚面完百度的 Agent 开发岗,我才发现:世界就是个巨大的草台班子
java·开发语言·人工智能·spring·百度·langchain
微小冷3 小时前
在不同空间中展示数据(欧式、球面、庞加莱圆盘)
python·双曲空间·微分几何·geomstats·庞加莱圆盘·球面
felixking3 小时前
C++20 协程
开发语言·c++·协程
weixin_431600443 小时前
Agent Workflow 学习向:Code 节点,比模板更强的变量加工
后端·python·学习·ai·
讲温控就好了4 小时前
从医疗影像到能源存储——芯片冷却温控技术的跨行业赋能
人工智能·python·能源
DeepVisionary4 小时前
从 Qwen3.8-27B 把原生多模态、原生 FP8、桌面级 Agent 三件事一次集齐,看开源大模型的“工业化拐点“
python·自动化
Zane1994124 小时前
CAS 与原子类:Java 如何实现无锁编程
java·开发语言