1

I am trying to upload a file to Rails 6 Activestorage api (using ReactJS), the docs for this are not very clear to me but after lots of searching, it seems best to use:

obj.attachment_name.attach(file)

This works well if I have a file on the Rails end, however passing the file from the React to the Rails side is a bit tricky, the best option I found was to transform the file to base64 string & send it to the API

So how to convert a javascript file passed as base64 string on the Rails side to a file object?

I tried this answer, but surprisingly, it doesn't convert the string to a file (I wonder if that is because JS conversion is different than Rails base64 conversion)

Note: This works well to encode & decode files using ruby only

# Testing plain ruby
# Open the file you wish to encode
file_path = "/Users/...path/some_image.jpg"
data = File.open(file_path).read

# Encode the image
encoded = Base64.encode64(data)

# Why this block doesn't work for a JS encoded base64 string??
# i.e, if I passed encoded string from JS here, it won't work

File.open("some_filename", "wb") do |file|
  file.write(Base64.decode64(encoded))
end
Ahmed Elkoussy
  • 8,162
  • 10
  • 60
  • 85
  • I think your problems is about escape character. I had this issue once, passed a p12 file as base64 string to rails, and have to save it as a file object. And my problem was clearly the escape character. You can take a look at this question and answer: https://stackoverflow.com/questions/60426316/why-ruby-controller-would-escape-the-parameters-itself/60427673#60427673 – KSD Putra Mar 03 '20 at 02:55

0 Answers0