David Routen
David Routen

Reputation: 349

Rails send_data using Rmagick image.to_blob not working

My application creates customized labels depending on an object's properties (make, model, etc.) and successfully saves them to the server. I'm trying to get it to send_data the image (using to_blob) directly to the browser so the user can immediately open and print the image, instead of saving it to the server first. I'm having a lot of trouble getting the sending to the browser part to work.

I'm using Rails (4.0.0) and rmagick (2.13.4). Please let me know if I can share any other information. Here's the code:

VIEW

<%= link_to fa_icon('qrcode', text: 'Print'),
    labels_path(@warranty_item.qr_code, { format: :png }), 
    method: :post, remote: true, class: 'btn btn-xs btn-warning' %>

CONTROLLER

require 'rmagick'

def create
  respond_to do |format|
    format.png do
      @img = Magick::Image.new(280, 100) { self.background_color = blue' }
      @img.format = 'png'
      @img_blob = @img.to_blob

      send_data @img_blob, filename: 'test_label.png', disposition: 'inline', type: 'image/png'
    end
  end
end

In Rails' logs, this goes off without a hitch; no errors, no warnings, only a: Sent data test_label.png (0.7ms)

If I run @img.to_blob in the Rails console, it gives me this:

"\x89PNG\r\n\x1A\n\x00\x00\x00\rIHDR\x00\x00\x01 \x00\x00\x00$\x01\x03\x00\x00\x00\x13\xABua\x00\x00\x00\x04gAMA\x00\x00\xB1\x8F\v\xFCa\x05\x00\x00\x00 cHRM\x00\x00z&\x00\x00\x80\x84\x00\x00\xFA\x00\x00\x00\x80\xE8\x00\x00u0\x00\x00\xEA`\x00\x00:\x98\x00\x00\x17p\x9C\xBAQ<\x00\x00\x00\x06PLTE\x00\x00\xFF\xFF\xFF\xFF{\xDC\x99,\x00\x00\x00\x01bKGD\x00\x88\x05\x1DH\x00\x00\x00\x14IDAT8\xCBc`\x18\x05\xA3`\x14\x8C\x82Q@,\x00\x00\x054\x00\x01\xEA\xAF\x9B \x00\x00\x00\x00IEND\xAEB`\x82"

However, if I use the logger, Rails.logger.info @img.to_blob it gives me this:

�PNG

IHDR $�uagAMA��
           �a  cHRMz&�����u0�`:�p��Q<PLTE����{ܙ,bKGD�HIDAT8�c`�`��Q@,4ꯛ IEND�B`�

Like I'd mentioned above, if I simply save the image, @img.write('test_label.png'), it works perfectly. What am I doing wrong? What am I missing? The code executes, tested in the console it works, but it does not send the image data to the user's browser/downloads file so they can open it. Please help!

Upvotes: 0

Views: 1430

Answers (1)

TsaiKoga
TsaiKoga

Reputation: 13404

It cannot work. Your link with 'remote: true' is an ajax request. You can't download a image to disk from JS. It's a security concern.

read here: enter link description here

Upvotes: 1

Related Questions