Skip to content

Instantly share code, notes, and snippets.

@julianrubisch
Last active February 18, 2022 12:03
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julianrubisch/4d5f90089b82f7ea47045be0eee51064 to your computer and use it in GitHub Desktop.
Save julianrubisch/4d5f90089b82f7ea47045be0eee51064 to your computer and use it in GitHub Desktop.
ActiveStorage DirectUpload via Faraday
require "faraday"
require "faraday/multipart"
token = ARGV.shift
absolute_path = File.expand_path(ARGV.shift)
# TODO how could we require "active_storage/blob" without eager loading the whole app
blob = ActiveStorage::Blob.build_after_unfurling(io: File.open(absolute_path), filename: File.basename(absolute_path))
conn_pre = Faraday.new(
url: "http://localhost:3000",
) do |f|
f.request :url_encoded
end
res_pre = conn_pre.post("/rails/active_storage/direct_uploads", {blob: blob.attributes.slice("filename", "byte_size", "checksum", "content_type", "metadata")})
json = JSON.parse(res_pre.body) if res_pre.body.present?
puts "Reponse Status Code: #{res_pre.status}"
exit unless res_pre.status == 200
direct_upload_data = json&.fetch("direct_upload")
conn_blob = Faraday.new(
url: "http://localhost:3000",
headers: direct_upload_data["headers"].merge({"Content-Length" => blob.byte_size.to_s, "Transfer-Encoding" => "chunked"})
) do |f|
f.request :multipart
f.adapter Faraday.default_adapter
end
res_blob = conn_blob.put(direct_upload_data["url"], Faraday::UploadIO.new(
absolute_path,
blob.content_type
))
puts "Success" if res_blob.status >= 200 && res_blob.status < 300
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment