Skip to content

Instantly share code, notes, and snippets.

@zeph1rus
Created July 30, 2023 22:19
Show Gist options
  • Save zeph1rus/6bd7c762e8090f695291572537dbcd20 to your computer and use it in GitHub Desktop.
Save zeph1rus/6bd7c762e8090f695291572537dbcd20 to your computer and use it in GitHub Desktop.
Uploading a file async in a form using System.Net.HttpClient in F# and POST requests
let createFileHttpContent (path:string):MultipartFormDataContent =
let file = System.IO.File.OpenRead(path)
let content = new MultipartFormDataContent()
let fileContent = new StreamContent(file)
fileContent.Headers.ContentType <- MediaTypeHeaderValue.Parse("multipart/form-data")
content.Add(fileContent, "file", path)
content
let uploadFile path =
async {
use fileContent = createFileHttpContent path
use client = new HttpClient()
try
let! response = Async.AwaitTask(client.PostAsync(constructUrl, fileContent))
printfn $"{path} - {response.StatusCode}"
match response.StatusCode with
| HttpStatusCode.OK -> printfn "Success"
| _ -> ()
with error -> printfn $"%s{error.Message}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment