Are there any multipart/form-data parser in C# - (

2019-01-17 05:18发布

I am just trying to write a multipart parser but things getting complicated and want to ask if anyone knows of a ready parser in C#!

Just to make clear, I am writing my own "tiny" http server and need to pars multipart form-data too!

Thanks in advance, Gohlool

5条回答
对你真心纯属浪费
2楼-- · 2019-01-17 05:35

Check out the new MultipartStreamProvider and its subclasses (i.e. MultipartFormDataStreamProvider). You can create your own implementation too if none of the built in implementations are suitable for you use case.

查看更多
闹够了就滚
3楼-- · 2019-01-17 05:49

With Core now you have access to a IFormCollection by using HttpContext.Request.Form.

Example saving an image:

        Microsoft.AspNetCore.Http.IFormCollection form;
        form = ControllerContext.HttpContext.Request.Form; 

        using (var fileStream = System.IO.File.Create(strFile))
        {
            form.Files[0].OpenReadStream().Seek(0, System.IO.SeekOrigin.Begin);
            form.Files[0].OpenReadStream().CopyTo(fileStream);
        }
查看更多
手持菜刀,她持情操
4楼-- · 2019-01-17 05:51

I've had some issues with parser that are based on string parsing particularly with large files I found it would run out of memory and fail to parse binary data.

To cope with these issues I've open sourced my own attempt at a C# multipart/form-data parser here

See my answer here for more information.

查看更多
贼婆χ
5楼-- · 2019-01-17 05:54

I open-sourced a C# Http form parser here.

This is slightly more flexible than the other one mentioned which is on CodePlex, since you can use it for both Multipart and non-Multipart form-data, and also it gives you other form parameters formatted in a Dictionary object.

This can be used as follows:

non-multipart

public void Login(Stream stream)
{
    string username = null;
    string password = null;

    HttpContentParser parser = new HttpContentParser(stream);
    if (parser.Success)
    {
        username = HttpUtility.UrlDecode(parser.Parameters["username"]);
        password = HttpUtility.UrlDecode(parser.Parameters["password"]);
    }
}

multipart

public void Upload(Stream stream)
{
    HttpMultipartParser parser = new HttpMultipartParser(stream, "image");

    if (parser.Success)
    {
        string user = HttpUtility.UrlDecode(parser.Parameters["user"]);
        string title = HttpUtility.UrlDecode(parser.Parameters["title"]);

        // Save the file somewhere
        File.WriteAllBytes(FILE_PATH + title + FILE_EXT, parser.FileContents);
    }
}
查看更多
仙女界的扛把子
6楼-- · 2019-01-17 05:57

I had a similar problem that i recently solved thanks to Anthony over at http://antscode.blogspot.com/ for the multipart parser.

Uploading file from Flex to WCF REST Stream issues (how to decode multipart form post in REST WS)

查看更多
登录 后发表回答