I am trying to download a file from gmail thru their API with the following code:
case GmailService.message_attachment(token, user.email, attachment.messageID, attachment.attachmentID, []) do
{:ok, file} -> File.write!("./attachments/#{attachment.filename}", file[“data”], [:write, { :enconding, :utf8 }])
{:error, reason} -> IO.puts(reason)
end
The attachment properly downloads and binds the data to “file” constant but I am unable to save the file correctly.
With the File.write command it creates the file to the specified directory, name and size but when I try to open it, it fails as if the file was corrupted.
I have the same scenario with Ruby on Rails and I use a File.Open with the encondig of the file and works fine.
Can anyone guide me on this issue? Do I need to use IO.binwrite?
You are explicitly using the encoding: :utf8 mode.
Does that mean your input data is actually encoded as UTF8? If not, try using :binary mode instead.
You only need IO.binwrite/2 or IO.write/2 if you open the file via File.open/2 or File.open/3. Check out the documentation for File.open/3 on how to do that.
If it is a PDF, the first four bytes must match<<0x25, 0x50, 0x44, 0x46,>> ("%PDF"), if they don’t, your incomming stream is probably encoded, please take a look into your full response struct, if you can pull some header information out from it which tells you more about the encoding.
Using some online tools, it seems in fact that your first couple of bytes (taken from raw) match the base64-encoded version of "%PDF", which is JVBERg==, so you need to base64 decode your data before writing it to disc.
A google search for “gmail download attachment base64 dash” turned up this SO post and I quote the answer:
I just found out the gmail api return the attachment content in base64url format where the ‘+’ and ‘/’ characters of standard Base64 are respectively replaced by ‘-’ and ‘_’.
There is actually a variant of Base 64 that uses those characters in order to make them »URL and Filename safe«. Elixir supports it through Base.url_decode64!/2.