HttpMultipartParser

repository·develop·Indexed 43 days ago

https://github.com/http-multipart-data-parser/httpmultipartparser

A .NET library for parsing multipart/form-data streams. It features a non-streaming API for small payloads and a high-performance streaming API via StreamingMultipartFormDataParser for efficient handling of large file uploads. Supports .NET Standard 2.0 and .NET 8.0.

Tokens
935
Snippets
3
Records
4
Agent score
6%

What's inside HttpMultipartParser

  1. Parse multipart/form-data using Non-Streaming mode

    develop

    Non-streaming parsing is simple but should not be used for very large files as it attempts to read the entire stream into memory.

    Use MultipartFormDataParser.Parse (synchronous) or MultipartFormDataParser.ParseAsync (asynchronous) to process the stream. Once parsed, you can retrieve parameter values using GetParameterValue or GetParameterValues (for multiple values of the same name), and access file data via the Files collection.

    // Synchronous parsing
    var parser = MultipartFormDataParser.Parse(stream);
    
    // Asynchronous parsing
    var parser = await MultipartFormDataParser.ParseAsync(stream).ConfigureAwait(false);
    
    // Retrieve single parameter
    var username = parser.GetParameterValue("username");
    
    // Retrieve multiple values for the same parameter name
    var checkboxResponses = parser.GetParameterValues("checkbox");
    
    // Access files
    foreach(var file in parser.Files)
    {
        string filename = file.FileName;
        Stream data = file.Data;
    }
  2. Parse multipart/form-data using Streaming mode

    develop

    Streaming mode is designed to handle large files efficiently by processing data as it arrives without reading the entire stream at once.

    To use it:

    1. Instantiate a StreamingMultipartFormDataParser with your input stream.
    2. Subscribe to the ParameterHandler and FileHandler delegates to process data chunks as they are received.
    3. Call parser.Run() or parser.RunAsync() to begin processing.

    This approach allows you to write file chunks directly to a destination (like a FileStream) as they are parsed.

    var parser = new StreamingMultipartFormDataParser(stream);
    
    // Handle parameters as they arrive
    parser.ParameterHandler += parameter => DoSomethingWithParameter(parameter);
    
    // Handle file chunks as they arrive
    parser.FileHandler += (name, fileName, type, disposition, buffer, bytes, partNumber, additionalProperties) =>
    {
        // Example: Write the buffer chunk to a file stream
        filestream.Write(buffer, 0, bytes);
    };
    
    // Optional: Handle stream closure
    parser.StreamClosedHandler += () => { /* cleanup */ };
    
    // Execute parsing
    await parser.RunAsync().ConfigureAwait(false);