How to Upload Multiple Files to pdfRest in .NET with C#

Learn how to Upload Multiple Files to pdfRest in .NET with C# by calling Upload Files API Tool by pdfRest.
Share this page

Upload Multiple Files in One C# Request

Document workflows often begin with a related set of files rather than a single PDF. The pdfRest Upload Files API Tool lets a .NET application upload multiple local files in one multipart request to /upload. The response associates each original filename with a unique resource ID that can be passed into later pdfRest operations.

Pre-uploading is optional because processing tools can accept files directly. It is useful when several steps will reuse the same inputs or when the application wants to separate transfer from processing. Once the files have resource IDs, subsequent API calls can use compact JSON bodies instead of uploading the same binaries again. This reduces repeated transfer and makes multi-step request logic easier to track.

For example, a C# claims portal can upload a claim form, supporting photographs, and a policy document together. The application records each returned resource ID, passes the relevant PDFs to Merge PDFs, and retains the image IDs for other processing. A single intake request keeps the submitted names and server resources aligned without requiring a separate upload call for every item.

This adapted example accepts multiple file paths, adds each file under the repeated multipart field name file, and prints the JSON response.

C# Multiple-File Upload Example

Set PDFREST_API_KEY in the environment and optionally set PDFREST_URL to select the US or EU Cloud API. Pass at least two valid file paths to the sample. The application should validate its own allowed file types and size limits before constructing the request.

/*
 * What this sample does:
 * - Uploads multiple files as resources using multipart/form-data.
 * - Routed from Program.cs as: `dotnet run -- upload-multiple inputFile1 inputFile2 [...]`.
 *
 * Setup (environment):
 * - Copy .env.example to .env
 * - Set PDFREST_API_KEY=your_api_key_here
 * - Optional: set PDFREST_URL to override the API region. For EU/GDPR compliance and proximity, use:
 *     PDFREST_URL=https://eu-api.pdfrest.com
 *   For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
 *
 * Usage:
 *   dotnet run -- upload-multiple /path/to/input1.pdf /path/to/input2.pdf
 *
 * Output:
 * - Prints the JSON response (resource metadata). Validation errors exit non-zero.
 */

using System.Text;

namespace Samples.EndpointExamples.MultipartPayload
{
    public static class Upload
    {
        public static async Task Execute(string[] args)
        {
            if (args == null || args.Length < 2)
            {
                Console.Error.WriteLine("upload-multiple requires inputFile1 inputFile2 [...]");
                Environment.Exit(1);
                return;
            }

            foreach (var inputPath in args)
            {
                if (!File.Exists(inputPath))
                {
                    Console.Error.WriteLine($"File not found: {inputPath}");
                    Environment.Exit(1);
                    return;
                }
            }

            var apiKey = Environment.GetEnvironmentVariable("PDFREST_API_KEY");
            if (string.IsNullOrWhiteSpace(apiKey))
            {
                Console.Error.WriteLine("Missing required environment variable: PDFREST_API_KEY");
                Environment.Exit(1);
                return;
            }

            var baseUrl = Environment.GetEnvironmentVariable("PDFREST_URL") ?? "https://api.pdfrest.com";

            using (var httpClient = new HttpClient { BaseAddress = new Uri(baseUrl) })
            using (var request = new HttpRequestMessage(HttpMethod.Post, "upload"))
            {
                request.Headers.TryAddWithoutValidation("Api-Key", apiKey);
                request.Headers.Accept.Add(new("application/json"));
                var multipartContent = new MultipartFormDataContent();

                foreach (var inputPath in args)
                {
                    var byteArray = File.ReadAllBytes(inputPath);
                    var byteAryContent = new ByteArrayContent(byteArray);
                    multipartContent.Add(byteAryContent, "file", Path.GetFileName(inputPath));
                    byteAryContent.Headers.TryAddWithoutValidation("Content-Type", "application/octet-stream");
                }

                request.Content = multipartContent;
                var response = await httpClient.SendAsync(request);
                var apiResult = await response.Content.ReadAsStringAsync();

                Console.WriteLine("API response received.");
                Console.WriteLine(apiResult);
            }
        }
    }
}

Starting point: pdfRest Upload Files multipart C# sample

Repeat the file Field for Each Local File

MultipartFormDataContent represents the request body. Add every local file as a separate content part with the same form field name, file, and its own original filename. The Upload Files endpoint recognizes the repeated field and returns a resource entry for each uploaded item. Do not combine local file parts with url fields in the same request.

The sample follows the official repository's ByteArrayContent pattern for clarity and repeats that pattern for every path. For larger files or batches, adapt the request to use StreamContent so the application does not hold all file bytes in memory at once. The total size of all files in the call is subject to the upload limit for the account's plan, even though the tool does not impose a separate file-count limit.

The response is JSON, but the local file upload request itself is multipart form data. Parse the response collection by filename and resource ID, verify that every expected file is present, and store the mapping with the document job. Do not rely only on array position if filenames provide a safer association.

Choose the Correct Upload Method

Multiple local files require multipart form data. A single local file can alternatively be sent as a raw binary request with application/octet-stream and a Content-Filename header. Files already hosted at public URLs can be submitted by repeating the endpoint's url parameter instead of downloading them into the application first. Local files and public URLs cannot be mixed in one call.

The repository file currently located under “JSON Payload” for C# Upload sends one raw binary file; it is not a JSON request and does not demonstrate multiple-file upload. For that reason, this tutorial should not describe it as the common JSON-payload alternative. The JSON benefit appears in subsequent processing calls, where the resource IDs returned by Upload Files can replace new multipart uploads.

Check the HTTP status and response schema before starting downstream work. Add appropriate timeouts and cancellation, keep the API key out of source control, and avoid logging document content. Use API Lab to inspect upload behavior and consult the Upload Files API reference for current file, URL, and response requirements.

Generate a self-service API Key now!
Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.