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')
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)
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__))
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
|