How to save a base64 string as an image using ruby

前端 未结 4 1113
抹茶落季
抹茶落季 2020-11-29 23:26

I\'m integrating my Ruby on Rails app with a usps shipping system. Once you make a postage request, you pay for that postage and it\'s nonrefundable.

Postage reques

4条回答
  •  孤街浪徒
    2020-11-30 00:17

    Other answers are pretty close, but usually assume that base64 stream will contain PNG data. This is not always the case so I suggest to use mime types library to establish correct file extension:

    REGEXP = /\Adata:([-\w]+\/[-\w\+\.]+)?;base64,(.*)/m
    
    data_uri_parts = data_url.match(REGEXP) || []
    extension = MIME::Types[data_uri_parts[1]].first.preferred_extension
    file_name = "myfilename.#{extension}"
    
    File.open(file_name, 'wb') do |file|
        file.write(Base64.decode64(data_uri_parts[2]))
    end
    

提交回复
热议问题