Dougui
Dougui

Reputation: 7230

Upload an image from JSON with rails

I have an application created with PhoneGap and Backbone. I upload a file as JSon and my server receive data like this :

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/...

I'm trying to write the file like this :

File.open("#{Rails.root}/public/images/#{self.id}.jpg", "w+") do |f|
  f.write(data)
end

It's not working and I don't know what to do. When I'm trying to open the file I have this message "Not a JPEG file: starts with 0x64 0x61".

Do you have a solution?

Upvotes: 1

Views: 388

Answers (3)

pre
pre

Reputation: 3506

For me, the following was the solution: (Note the binary write option, when opening the file)!

File.open("#{Rails.root}/public/images/#{self.id}.jpg", "wb") do |f|
   f.write Base64.decode64(data)
end

Upvotes: 0

Dougui
Dougui

Reputation: 7230

The solution was this :

f.write Base64.decode64(data).force_encoding('UTF-8') 

Upvotes: 1

Yuriy Goldshtrakh
Yuriy Goldshtrakh

Reputation: 2014

you need to decode the data first.

try:

File.open("#{Rails.root}/public/images/#{self.id}.jpg", "w+") do |f|
  decoded_data = Base64.decode64(data)
  image_data = StringIO.new(decoded_data)
  f.write(image_data)
end

Upvotes: 0

Related Questions