1 Reply Latest reply on Sep 6, 2013 3:47 PM by Hector Meza

    how to decode a base64 file in ruby?

    Hector Meza


      I am trying to take a file that was encoded with base64  from the webserver and decode it, then save it on the mobile device.

      The file seems to get corrupted - I believe because it is binary.  looking for a way to keep the binary integrity

       

      the following is a test sample that I have been using


      orig_name = 'base64.bin'
      new_file = 'new_decode.txt'
      doc_data = File.read(orig_name)

      f = File.new(new_file, "wb")

      require 'base64'
      file_bin_data = Base64.decode64(doc_data)
           
      f.write(file_bin_data)

      f.close

       

      the new file data is corrupted - attaching the orig test file (word doc), Base64.bin transfer file, and newly created (corrupt) file

      thanks

        • Re: how to decode a base64 file in ruby?
          Hector Meza

          I figured it out - the following code took care of the issue

           

          orig_name = 'base64.bin'

          new_file = 'new_decode.docx'

          doc_data = File.open(orig_name, 'rb').read

          require 'base64'

          contents = Base64.decode64(doc_data)

          File.open(new_file, 'wb') { |file| file << contents }

           

          the original word doc (my test sample) was converted to base64.bin, I transferred the file and ran the above code.  opened the file with "rb" options,  decoded the base64 into contents and inputed it into a new file.  I can open the new file with word and it is all there!

           

          HM