3

I'm struggling implementing a POST request with image attachment with the Julia HTTP package. In Python I can do (source from Pushover):

import requests
r = requests.post("https://api.pushover.net/1/messages.json", data = {
  "token": "APP_TOKEN",
  "user": "USER_KEY"
},
files = {
  "attachment": ("image.jpg", open("myimage.jpg", "rb"), "image/jpeg")
})

How can I do such a file attachment in simple ways with Julia/HTTP or another Julia package?

Many thanks!

1 Answer 1

2

This should be the equivalent request using HTTP.jl:

import HTTP
url = "http://localhost:8080" # check request with e.g. netcat -lp 8080
open("cat.jpg") do io
    headers = []
    data = [
        "token" => "APP_TOKEN",
        "user" => "USER_KEY",
        "attachment" => io,
    ]
    body = HTTP.Form(data)
    HTTP.post(url, headers, body)
end

The filename (cat.jpg) and content type (image/jpeg) is inferred from the io.


If you need better control, for example if you want the filename in the request to differ from the filename on disk, or if you want to manually specify Content-Type, you can manually construct a HTTP.Multipart entry, like this:

data = [
    "token" => "APP_TOKEN",
    "user" => "USER_KEY",
    "attachment" => HTTP.Multipart("other_filename.jpg", io, "image/png"),
]

You can compare/verify the request from HTTP.jl with the one from requests by using something like

$ netcat -lp 8080

and send the requests to http://localhost:8080.

1
  • Thanks a lot for the detailed example and explanation. Works perfectly.
    – Marian
    Feb 28, 2021 at 12:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.