python flask预览PDF的接口
@app.route('/viewPdfById/<id>',methods = ['get'])
def viewPdf(id):
id = int(id)
con = mysql.connect(host="192.168.10.71", port=3306, user="user", passwd="passwd", db="jibei", charset="utf8mb4")
mycursor = con.cursor()
# 从数据库根据id查询文件名字
sql = "SELECT filename FROM table WHERE id = '%s' "%(id)
mycursor.execute(sql)
infos = mycursor.description
fileds = [info[0] for info in infos]
produce = mycursor.fetchone()
# 将查询结果组织成字典的形式
dic = dict(zip(fileds, produce))
headers = ("Content-Disposition", f"inline;filename={dic['filename']}.pdf") # 文件预览
as_attachment = False
file_path = 'C:\\Users\\user\\Desktop\\pdf\\{}'.format(str(dic['filename']))
print(file_path)
response = make_response(send_file(file_path, as_attachment=as_attachment))
response.headers[headers[0]] = headers[1]
return response
if __name__ == '__main__':
app.config['JSON_AS_ASCII'] = False
app.run(host='127.0.0.1', port=8888)
http://localhost:5000/viewPdfById/2
这个2就是PDF在库里面对应的id