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