Vin*_* Le 2 ruby png ruby-on-rails image-rendering
我有一个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
Run Code Online (Sandbox Code Playgroud)
我已经添加:
Mime::Type.register "image/png", :png
Run Code Online (Sandbox Code Playgroud)
到config/initializers/mime_types.rb
我在其控制器中引用并呈现png文件:
render :inline => @object.body.string, :content_type => @object.content_type || "img/png", :layout => false
Run Code Online (Sandbox Code Playgroud)
编辑:
这是控制器中的方法
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
Run Code Online (Sandbox Code Playgroud)
结束
使用该send_data
方法发送二进制文件:
send_data(@object.body.string,
type: @object.content_type || 'image/png',
disposition: 'inline')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3112 次 |
最近记录: |