FLASK 上传损坏的图像

时间:2021-03-29 19:52:14

标签: 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 之后,图像就坏了。

enter image description here

1 个答案:

答案 0 :(得分:1)

通常,Web 服务器将处理大量内容 (nginx)。如果您尝试保存内容,那么最好的选择是将它们保存在某个位置的某处,并使用 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)
相关问题