【发布时间】:2015-12-10 16:43:59
【问题描述】:
我有一个 Rails 应用程序,我试图在其中显示 PNG 文件,但出现此错误:
ActionView::Template::Error (Your template was not saved as valid UTF-8. Please either specify UTF-8 as the encoding for your template in your text editor, or mark the template with its encoding by inserting the following as the first line of the template:
# encoding: <name of correct encoding>.
The source of your template was:
�PNG
IHDR#ͱ�) pHYs�]s� IDATx���g@SW�E��7�ZuV묣�Z�:j�mպm�Z��U[W�:�պZ�*�j���@�3� I���p��}
��?�
���b�X�/���Z�I�N111,ӧO��x�T�?x۶mU����vtt
我已添加:
Mime::Type.register "image/png", :png
到 config/initializers/mime_types.rb
我在其控制器中引用和渲染 png 文件:
render :inline => @object.body.string, :content_type => @object.content_type || "img/png", :layout => false
编辑:
这是控制器中的方法
def read_data
resource = Aws::S3::Resource.new(client: @new_client)
if @files.size == 0 && @links.size == 0 && resource.bucket(@bucket.name).objects.first != nil && !request.original_url.end_with?('/')
if request.original_url.split('/')[-1] != @bucket.name && resource.bucket(@bucket.name).object(@prefix).exists?
@object = @new_client.get_object(bucket: @bucket.name, key: @prefix)
if @prefix.present? && @object.last_modified && (@object.content_type.match(/text/) || @object.content_type.match("application/json") || @prefix.end_with?('.json') || @prefix.end_with?('.html') || @prefix.end_with?('.txt') || @prefix.end_with?('.xml') || (@object.content_length > 0 && @object.content_type == ""))
render :inline => @object.body.string, :content_type => @object.content_type || "text/plain", :layout => false
elsif @prefix.end_with?('.png')
send_data(@object.body,
:type => @object.content_type || "image/png",
:disposition => 'inline')
else
redirect_to resource.bucket(@bucket.name).object(@prefix).presigned_url(:get, expires_in: 8) #presigned url expires after 8 ms
end
end
end
结束
【问题讨论】:
-
您需要了解 HTML 的工作原理。二进制对象,如图像不嵌入 HTML 中,它们使用“统一资源定位器”(URLs)引用,然后浏览器从 URL 的主机部分中引用的服务器重新请求。 HTML 绝不包含二进制数据,它只包含文本。如果您希望浏览器下载某些内容,您可以将数据作为单独的流发送,但这是一个不同的过程。
标签: ruby-on-rails ruby png image-rendering