• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

flask上传图片解决方案

武飞扬头像
熊子q
帮助1

flask上传图片解决方案

一、前端

前端的form表单必须加enctype=“multipart/form-data” 属性,method必须为post

示例代码如下:

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
</head>
<body>
<form method="post" action="/register" enctype="multipart/form-data">
    <h3>注册</h3>
    <input type="file" name="photo">
    <input type="text" placeholder="账号" name="username">
    <input type="text" placeholder="密码" name="pwd">
    <button style="margin-top: 10px" type="submit">注册账号</button>
</form>
</body>
</html>
学新通

网页截图为:

学新通

二、后端

我用的后端是flask,下面是对应的路由:

@app.route('/register', methods=['POST'])
def register():

    img = request.files.get('photo') # 从post请求中获取图片数据
    suffix = '.'   img.filename.split('.')[-1] # 获取文件后缀名
    basedir = os.path.abspath(os.path.dirname(__file__)) # 获取当前文件路径
    photo = '/static/uploads/'   str(int(time.time()))   suffix # 拼接相对路径
    img_path = basedir   photo # 拼接图片完整保存路径,时间戳命名文件防止重复
    img.save(img_path) # 保存图片
	print(img_path)
    
    # 其他参数用request.form字典获取
    username = request.form.get('username', '')
    pwd = request.form.get('pwd', '')
    # 这些值都可直接保存到数据库中
    print(photo, username, pwd)
    return {'msg':'ok'}
学新通

后端截图:

学新通

三、结语

如果你做的系统中多次用到上传图片到服务器的话,建议将保存图片作为单独的方法拉出来,方便多次调用。下面是我写的接口:

# 保存图片根路径
BASEDIR = os.path.abspath(os.path.dirname(__file__))

# 保存图片到/static/uploads文件夹,并以时间戳命名
# 返回/static/uploads/filename
def saveImg(img):
    # 时间戳作为文件名
    img_path = BASEDIR   '/static/uploads/'   str(int(time.time()))   '.'   img.filename.split('.')[-1]
    img.save(img_path)
    print(img_path)
    photo_path = '/static/uploads/'   str(int(time.time()))   '.'   img.filename.split('.')[-1]
    print(photo_path)
    return photo_path

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhggfagb
系列文章
更多 icon
同类精品
更多 icon
继续加载