Search code examples
postservicestackmultifile-uploader

ServiceStack - Posting multiple files with one POST request


I'm struggling with this issue for several hours, and I can't find any solution. Does someone used ServiceStack to upload multiple files with one POST request?

I was trying to use PostFile:

  FileInfo fi = new FileInfo("ExampleData\\XmlAPI.xml");
  var client = new XmlServiceClient("http://localhost:1337");
  client.PostFile<DefaultResponse>("/test", fi, "application/xml");

But here I am able to add only one file to the request. My second shot was to use LocalHttpWebRequestFilter but inside there is only a extension method which also allows to post only one file.


Solution

  • Multiple File Upload APIs have been added to all .NET Service Clients in v4.0.54 that allow you to easily upload multiple streams within a single HTTP request. It supports populating Request DTO with any combination of QueryString and POST'ed FormData in addition to multiple file upload data streams:

    using (var stream1 = uploadFile1.OpenRead())
    using (var stream2 = uploadFile2.OpenRead())
    {
        var client = new JsonServiceClient(baseUrl);
        var response = client.PostFilesWithRequest<MultipleFileUploadResponse>(
            "/multi-fileuploads?CustomerId=123",
            new MultipleFileUpload { CustomerName = "Foo,Bar" },
            new[] {
                new UploadFile("upload1.png", stream1),
                new UploadFile("upload2.png", stream2),
            });
    }
    

    Or using only a Typed Request DTO. The JsonHttpClient also includes async equivalents for each of the new PostFilesWithRequest APIs:

    using (var stream1 = uploadFile1.OpenRead())
    using (var stream2 = uploadFile2.OpenRead())
    {
        var client = new JsonHttpClient(baseUrl);
        var response = await client.PostFilesWithRequestAsync<MultipleFileUploadResponse>(
            new MultipleFileUpload { CustomerId = 123, CustomerName = "Foo,Bar" },
            new[] {
                new UploadFile("upload1.png", stream1),
                new UploadFile("upload2.png", stream2),
            });
    }