Python FLASK上载损坏的图像
我正在尝试上传图片并在URL中显示 我的服务器:Python FLASK上载损坏的图像,python,flask,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'])
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
code:
<html>
<head>
<title>show_pic</title>
</head>
<body>
<img src="{{url_for('static', filename=file1)}}" align= "middle" />
</body>
</html>
展示图片
然后,我使用POST请求上传图片,这并没有显示任何问题。但是当我在同一个端点上使用GET后,图像被破坏了
通常,web服务器将处理大量内容(nginx)。如果您正试图保存内容,那么最好的选择是将其保存在某个位置的某个位置,并将与get image一起使用作为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)
非常感谢,您的快速修复确实有效。但是我仍然对
send\u from\u directory
感到困惑,因为我只看到了让文件下载示例的用法。