Created
July 30, 2023 22:19
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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