首页 > 解决方案 > 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 之后,图像就坏了。

在此处输入图像描述

标签: pythonflask

解决方案


通常,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)

推荐阅读