我正在使用第三方应用程序,并且现在要上传具有Rails活动存储的图像,我只能访问内联数据(例如:data:image / png; base64,iVBORw0KG ....) 然后如何使用活动存储进行存储?还是将其转换为Blob?
avatar.attach看起来仅适用于请求或表单中的blob或上载的文件
file = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAclBMVEX///8AAACSkpL19fXr6+tYWFhRUVHj4+NgYGCpqakXFxc5OTm1tbXw8PBtbW2AgIAfHx8KCgqhoaGenp5DQ0PS0tKmpqbCwsJJSUk6Ojq7u7sUFBRpaWnKysrb29vf3990dHQwMDCMjIwqKiqOjo4kJCSHyVX2AAAJSUlEQVR4nO2de5+qLBDHLU2z7J5d3LW0dt//W3za07YBMwghN3v8/XU+JxW+iwwMDkMQqCsMz8PFcqBTo3TWokJ6NUtOsVa4h+ZJ6JrtR7O80tt4pBYn13hBUCxWxvhu2m4cN2NmsP1+Nc8d8iUX43w3HRfOAKORBb4fuUJcW+K76XB2AZjaA7wNjg46484m4GBQZ28OeNP63QEHg41NQItGxg1idHRCuLKGmJiZZ0vIFuLQFaAtc1N+uyMc7CwAzha80qfzYWtdRD3AAmLGKXq8KyMNjz9tps2IxvtidEDLjbNEVwmbj2ZE030xQkstdK6pjJsJTQ8ac6zQvdYi8kkzotkXNUQK3OouRNATzSIiPtNSh4Gh9CUiNGlRoTGfFtoL2QsJDSLaeWPEhMZeVPjXPZjwviUITSHCKemXiWJkCA0hguH+28jqgmDMv2tlZOgHjuGniVKCSqoRjbTili3kYqAQzrQCkX6LGtVMER9mrLYsoX7EHdtBrma+DUkTap+Gp+yM8ai5gF/JE+rui4Bwqvf5D71AqBnRR0K9zpSPhHpb0U9CnebGU0KNg4avhPpa0VtCbX3RX0JdiB4Taho0PCbU1IpeE2oxN34T6hg0PCfUgOg7Yfu+6D1h677oP2HbQcN/wrYvahcI41YLK10gHIzaIHaCcDBu8bm2G4SDoXrJHSEclMold4WwVu6KXSEcjFRL7gyhclfsDuFBseTu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yqovS/EGHZnjw8qEh4atAEZ7qKM5UZoFtFSY5J/eyehMGIS/ge7wreLHohlTuh/hJwDc706YmCZZN9K5tNbSoy/GbWxNsD7K84ATJP7WbhYjSjnugtn55w3vqh9q9oz9aN+4TcC6w8VZBXp+EwUmr8poiLNO9J6pLcf07jbhEYsCVlPiKqM+X8xRRp7MavZSq0pI0TxvXtWsgWqu59gWVZC447saq4szEilHqzfRmstAxDCI6rf1grApzntt55/w8wWuKHcGjUVGycdiQ16qwsbwQhvtqYd/sjBZV+IJ5+Q/C7LvXlNtrHAAAAABJRU5ErkJggg=="
ite = Item.find(item_id)
ite.presentation.attach(file)
通过存储图像的tmp文件的当前工作方式:
ite = Item.find(item_id)
content_type = file[/(image\/[a-z]{3,4})|(application\/[a-z]{3,4})/]
content_type = content_type[/\b(?!.*\/).*/]
contents = file.sub /data:((image|application)\/.{3,}),/, ''
decoded_data = Base64.decode64(contents)
filename = 'img_' + Time.zone.now.to_s + '.' + content_type
File.open("#{Rails.root}/tmp/images/#{filename}", 'wb') do |f|
f.write(decoded_data)
end
ite.presentation.attach(io: File.open("#{Rails.root}/tmp/images/#{filename}"), filename: filename)
FileUtils.rm("#{Rails.root}/tmp/images/#{filename}")