title | type | description | num | previous-page | next-page |
---|---|---|---|---|---|
How to upload a file over HTTP? |
section |
Uploading a file over HTTP with sttp. |
28 |
http-client-json |
http-client-what-else |
{% include markdown.html path="_markdown/install-sttp.md" %}
To upload a file, you can put a Java Path
in the body of a request.
You can get a Path
directly using Paths.get("path/to/file")
or by converting an OS-Lib path to a Java path with toNIO
.
{% tabs 'file' class=tabs-scala-version %} {% tab 'Scala 2' %}
import sttp.client4.quick._
val file: java.nio.file.Path = (os.pwd / "image.png").toNIO
val response = quickRequest.post(uri"https://example.com/").body(file).send()
println(response.code)
// prints: 200
{% endtab %} {% tab 'Scala 3' %}
import sttp.client4.quick.*
val file: java.nio.file.Path = (os.pwd / "image.png").toNIO
val response = quickRequest.post(uri"https://example.com/").body(file).send()
println(response.code)
// prints: 200
{% endtab %} {% endtabs %}
If the web server can receive multiple files at once, you can use a multipart body, as follows:
{% tabs 'multipart' class=tabs-scala-version %} {% tab 'Scala 2' %}
import sttp.client4.quick._
val file1 = (os.pwd / "avatar1.png").toNIO
val file2 = (os.pwd / "avatar2.png").toNIO
val response = quickRequest
.post(uri"https://example.com/")
.multipartBody(
multipartFile("avatar1.png", file1),
multipartFile("avatar2.png", file2)
)
.send()
{% endtab %} {% tab 'Scala 3' %}
import sttp.client4.quick.*
val file1 = (os.pwd / "avatar1.png").toNIO
val file2 = (os.pwd / "avatar2.png").toNIO
val response = quickRequest
.post(uri"https://example.com/")
.multipartBody(
multipartFile("avatar1.png", file1),
multipartFile("avatar2.png", file2)
)
.send()
{% endtab %} {% endtabs %}
Learn more about multipart requests in the sttp documention.