本人是小白一枚,开始入手学习python,在学习过程中用到了上传图片这个东东,这里记录一些
上传文件的思路
1.把文件上传到服务器到一个文件夹中
2.服务器返回一个URL地址
写代码前一定要记得引入flask
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录完成</title>
</head>
<body>
<p>welcome {{username}}</p>
<form action="/upload" enctype="multipart/form-data" method="post" >
<input type="file" name="photo" />
<input type="submit" value="提交" >
</form>
{% if url %}
<img src="{{url}}">
{% endif%}
</body>
</html>
python代码
from flask import Flask, render_template, request, redirect, url_for
from werkzeug.utils import secure_filename
# 上传文件到服务器指定到文件夹中(一定要放在自己起服务到那个文件夹,不要放在本地的其他文件夹中,不然服务器访问不了你的文件)
UPLOAD_FOLDER = 'static/'
# 上传文件格式
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
app = Flask(__name__)
app.config['UPLOAD_POLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS
# 上传图片
@app.route('/upload',methods=['GET','POST'])
def upload_images():
if request.method == 'POST':
print('request======>',request.files.get('photo').filename) #get('photo')是input标签 name的名称,切忌写错!
file = request.files['photo']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_POLDER'],filename))
url = UPLOAD_FOLDER+filename
return render_template('hello.html',url = url)
效果从上传前到上传后到效果展示
网友评论