python - FLASK 上传损坏的图像
问题描述
我正在尝试上传图片并将其显示在 URL 中。
我的服务器:
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLDER = os.path.join(APP_ROOT, 'static/uploads')
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/post_pic',methods=['POST','GET'])
def post_picture():
if request.method == 'POST':
file1 = request.files['image']
path1 = os.path.join(app.config['UPLOAD_FOLDER'], file1.filename)
file1.save(path1)
return_status = {"success":"true"}
return jsonify(return_status)
list_of_files = glob.glob(UPLOAD_FOLDER + '/*') # get latest file
latest_file = max(list_of_files, key=os.path.getctime)
return render_template("show_pic3.html", file1=latest_file)
show_pic3.hrml
代码:
<html>
<head>
<title>show_pic</title>
</head>
<body>
<img src="{{url_for('static', filename=file1)}}" align= "middle" />
</body>
</html>
然后我使用 POST 请求上传没有显示任何问题的图片。但是在我在同一个端点上使用 GET 之后,图像就坏了。
解决方案
通常,Web 服务器将处理大量内容(nginx)。如果您尝试保存内容,那么最好的选择是将它们保存在某个位置的某个位置,并使用带有 get 图像的send_from_directory作为 API 调用。
快速解决您的问题的方法是/app/static/
在渲染之前将其替换为任何内容。
list_of_files = glob.glob(UPLOAD_FOLDER + '/*') # get latest file
latest_file = max(list_of_files, key=os.path.getctime).replace("/app/static/","")
return render_template("show_pic3.html", file1=latest_file)
推荐阅读
- flutter - Flutter 在自定义对话框之间导航和发送数据
- android - Navigation Jetpack 上的深层链接
- javascript - 当 processData 为 true 时,像 jQuery 在 Ajax 请求中一样处理 JS Fetch Api 请求的输入数据
- c++ - 通过引用传递参数时模板的显式实例化
- aws-step-functions - 在 SAM 模板中定义的本地运行 Step Function
- python-3.x - 在时间序列线性回归中获取第二天的预测值
- javascript - 如何更新第二个轴的数据 plotly javascript?
- python - ValueError:发现样本数量不一致的输入变量:[6, 1]
- javascript - How to use directive for external link in angular?
- python - Pandas 从 CSV 日期时间读取 - 日期和时间格式问题