在Rails中渲染PNG文件 [英] Render PNG file in Rails

查看:104
本文介绍了在Rails中渲染PNG文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Rails应用,试图显示PNG文件,但出现此错误:

I have a Rails app where I am trying to display a PNG file but I am getting this error:

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

to the config/initializers/mime_types.rb

我正在使用以下方法在其控制器中引用和渲染png文件:

I'm referencing and rendering the png file in its controller with:

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

结束

推荐答案

使用 send_data 发送二进制文件的方法:

Use the send_data method to send binary files:

send_data(@object.body.string, 
          type: @object.content_type || 'image/png', 
          disposition: 'inline')

这篇关于在Rails中渲染PNG文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆