近日做项目需要写一些前端代码,这是我的一些代码笔记,在这里分享一下
前端代码
<!DOCTYPE html>
<html>
<head>
<title>首页</title>
</head>
<body>
<div id="box">
<form id="uploadForm" enctype="multipart/form-data" >
<input type="file" name="file">
<input type="button" value="上传" id="upFileBtn">
</form>
</div>
<div id="img1" style="height:25%;width:25%;"></div>
</body>
<script type="text/javascript" src="static/js/jquery.js" ></script>
<script type="text/javascript">
$('#upFileBtn').click(function () {
var formFile = new FormData($('#uploadForm')[0])
$.ajax({
url:"/up_file",
type:"POST",
data:formFile,
processData:false,
contentType:false,
success: function (data) {
document.getElementById('img1').innerHTML=data
}
})
})
</script>
</html>
后台代码
#-*-coding:utf-8-*-
from flask import Flask,render_template,request
from flask_uploads import configure_uploads,UploadSet
import os,base64
app = Flask(__name__)
#配置上传文件存放路径
base=os.path.dirname(os.path.abspath(__file__))
base = os.path.join(base,'static')
app.config['UPLOADS_DEFAULT_DEST']=base
photo=UploadSet()
configure_uploads(app,photo)
@app.route('/up_file', methods=['GET', 'POST'])#接受并存储文件
def up_file():
if request.method == "POST":
#接收图片
photo.save(request.files['file'], 'img1', 'pic.png')#保存图片
#发送图片
img = open("static/files/img1/pic.png", 'rb')#读取图片文件
data = base64.b64encode(img.read()).decode()#进行base64编码
html = '''<img src="https://img-blog.csdnimg.cn/2022010708533623761.png" style="width:100%;height:100%;"/>'''#html代码
htmlstr = html.format(data)#添加数据
return htmlstr
@app.route('/',methods=['get','post'])
def index():
return render_template('index.html')
if __name__ == "__main__":
app.run()