Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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

like image 413
eestein Avatar asked Dec 08 '16 15:12

eestein


People also ask

How to post Multipart form data in c#?

Add("fileformat", "doc"); postParameters. Add("file", new FormUpload. FileParameter(data, "People. doc", "application/msword")); // Create request and receive response string postURL = "http://localhost"; string userAgent = "Someone"; HttpWebResponse webResponse = FormUpload.

What is the definition of Flurl?

Flurl is a modern, fluent, asynchronous, testable, portable, buzzword-laden URL builder and HTTP client library for . NET.


1 Answers

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
like image 100
Todd Menier Avatar answered Sep 21 '22 09:09

Todd Menier