Py上传文件

例如:简单的上传,需要将编码改为enctype="multipart/form-data

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传文件</title>
</head>
<body>
{{ msg }}<br>
{% if pic %}
<img src="/static/upload/{{ pic }}">
{% endif %}
{#文件上传编码格式 enctype="multipart/form-data"#}
<form action="/index" method="post" enctype="multipart/form-data">
    用户名:<input type="text" name="username"><br>
    头像:<input type="file" name="icons"><br>
    <input type="submit" value="提交">
</form>

</body>
</html>

页面:
在这里插入图片描述

设置想要上传到的路径
例:在这里插入图片描述

@app.route('/index',methods=['GET','POST'])
def index():
    if request.method=='GET':
        return render_template('index.html')
    else:
        #用request获取表单中的文件和用户名
        icons=request.files.get('icons')
        username=request.form['username']
        
        #设置要保存到的路径
        UPLOAD_DIR='static/upload'
        file_path=os.path.join(UPLOAD_DIR,icons.filename)
        #把文件保存在指定路径
        icons.save(file_path)
        
        #保存到数据库
        user=Users(name=username,pic=file_path)
        db.session.add(user)
        db.session.commit()
        msg='上传成功'
        return render_template('index.html',

例:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值