Search code examples
c#flurl

How can I upload a file and form data using Flurl?


I'm trying to upload a file with body content. Is PostMultipartAsync the only way?

On my C# backend code I have this:

var resource = FormBind<StorageFileResource>();
var file = Request.Files.First().ToPostedFile();

FormBind reads data from the request and fills the object.

By using PostMultipartAsync I know it should start like this:

.PostMultipartAsync((mp) => { mp.AddFile(name, stream, name)}), but I can't figure out how to add the object. Do you have any ideas on that?

This is my current try:

public static async Task<T> PostFileAsync<T>(string url, object data, string name, Stream stream, object queryString = null)
    where T : class
{
    return await HandleRequest(async () => queryString != null
        ? await url
            .SetQueryParams(queryString)
            .SetClaimsToken()
            .PostMultipartAsync((mp) => { mp.AddFile(name, stream, name)})
            .ReceiveJson<T>()
        : await url
            .SetClaimsToken()
            .PostMultipartAsync((mp) => mp.AddFile(name, stream, name))
            .ReceiveJson<T>());
}

Current request being made by the front end:

enter image description here


Solution

  • There are a variety of ways to add "parts" to a multipart POST with Flurl. I haven't added this to the docs yet but here's an example from the issue that basically demonstrates every possibility:

    var resp = await "http://api.com"
        .PostMultipartAsync(mp => mp
            .AddString("name", "hello!")                // individual string
            .AddStringParts(new {a = 1, b = 2})         // multiple strings
            .AddFile("file1", path1)                    // local file path
            .AddFile("file2", stream, "foo.txt")        // file stream
            .AddJson("json", new { foo = "x" })         // json
            .AddUrlEncoded("urlEnc", new { bar = "y" }) // URL-encoded                      
            .Add(content));                             // any HttpContent