Upload files to imgbb

Hello
I am trying to upload files to imbBB image hosting service. I am using liveview and I am in the place where the file can be uploaded to external place. Its the consume_uploaded_entry callback function that I named upload_static_file.

Here is the URL for the imgBB API for the case: https://api.imgbb.com/

Basically, what they are asking me to send to them are the following things: A binary file, base64 data, or a URL for an image. (up to 32 MB)

Here is my function:

defp upload_static_file(%{path: path}, socket) do

    IO.inspect("EMERAT")
    
    dest = Path.join("priv/static/images", Path.basename(path))

    # File.cp!(path, dest)

    request1 = %HTTPoison.Request{
      method: :post,
      url: "https://api.imgbb.com/1/upload",
      options: [],
      headers: [],
      params: [
        {~s|expiration|, ~s|600|},
        {~s|key|, ~s|SECRET|},
      ],
      body: {:multipart, [
        {~s|image|, ~s|#{dest}|}
    ]}
    }

    response = HTTPoison.request(request1)
    IO.inspect("This is what we get")
    IO.inspect(response)

    Routes.static_path(socket, "/images/#{Path.basename(dest)}")
  end

Can I turn my uploaded file to binary or base64? Also because I work from localhost, their URL option is not valid for my case. I think.

Can someone guide me how to achieve this?

I solved it. For those who are interested in, here is the solution:

defp upload_static_file(%{path: path}, socket) do

    IO.inspect("EMERAT")

    dest = Path.join("priv/static/images", Path.basename(path))

    # File.cp!(path, dest)

    {_, content } = File.read(path)

    b64 = Base.encode64(content)
    IO.inspect(b64)
    request1 = %HTTPoison.Request{
      method: :post,
      url: "https://api.imgbb.com/1/upload",
      options: [],
      headers: [],
      params: [
        {~s|expiration|, ~s|600|},
        {~s|key|, ~s|SECRET|},
      ],
      body: {:multipart, [
        {~s|image|, ~s|#{b64}|}
    ]}
    }

    response = HTTPoison.request(request1)
    IO.inspect("This is what we get")
    IO.inspect(response)

    # Routes.static_path(socket, "/images/#{Path.basename(dest)}")
  end
1 Like