在Rails中渲染PNG文件

我有一个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: . 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 

结束

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

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

在控制器操作上使用此代码:

 respond_with @resource do |format| # format.html { send_data @resource.body } # => Download the image file. format.html { send_data @resource.body, type: @resource.content_type || 'image/png', disposition: 'inline' } # => Show in browser page. end