背景
项目中要临时生成一些图片以供后续流程使用,本地没有问题,线上有点问题,需要添加一个预览的接口
知识储备
Content-Disposition
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Content-Disposition
实现
编码
import os
from flask import Flask, Response, jsonify, url_for
app = Flask(__name__)
PORT = 5000
HOST = '127.0.0.1'
DEBUGGER = True
@app.route('/<path:filename>')
def document_preview(filename):
response = Response(
open(rf'files/{filename}', 'rb'))
response.headers['Content-Type'] = '*/*'
response.headers['Content-Disposition'] = 'inline;'
response.status = 200
return response
@app.route('/')
def all_document():
res = []
for root, dirs, files in os.walk('files'):
for file in files:
s = url_for('document_preview', filename=file)
res.append(f'http://{HOST}:{PORT}' + s)
return jsonify(res)
效果
pdf及图片都是可以正常预览的,如果不能正常预览,看一下浏览器是否有自动下载插件