unosquare / embedio

A tiny, cross-platform, module based web server for .NET
http://unosquare.github.io/embedio
Other
1.47k stars 176 forks source link

File upload on 3.x #412

Closed gnh1201 closed 4 years ago

gnh1201 commented 4 years ago

I couldn't find examples like #60 for upload the file on 3.x. How to? thanks.

rdeago commented 4 years ago

Hello @gnh1201, thanks for using EmbedIO!

The code snippet @geoperez posted in #60, slightly simplified and ported to EmbedIO v3, should be as follows. Remember to include HttpMultipartParser in your dependencies.

[Route(HttpVerbs.Post, "/upload")]
public void UploadFile()
{
    var parser = new MultipartFormDataParser(context.Request.InputStream);
    var anyFileUploaded = false;
    foreach (var file in parser.Files)
    {
        anyFileUploaded = true;
        var path = Path.Combine(PathWhereYouPutUploadedFiles, file.FileName);
        using (var outputFile = File.Create(path))
            file.Data.CopyTo(outputFile);
    }

    if (!anyFileUploaded)
        throw HttpException.InvalidRequest("You need to post at least one file.");
}

The code above, which should be a method in a Web API controller, uses HttpMultipartParser to read file data from an upload request; it then saves each uploaded file on disk.

Disclaimer: I did not test the code. It should only be used as a starting point to develop your own upload method, but the basics are there. Feel free to ask if you need any further help.

geoperez commented 4 years ago

The library HttpMultipartParser has been updated, and the class MultipartFormDataParser constructor is obsolete. You can use the following snippet:

[Route(HttpVerbs.Post, "/upload")]
public async Task UploadFile()
{
    var parser = await MultipartFormDataParser.ParseAsync(Request.InputStream);
    var anyFileUploaded = false;

    foreach (var file in parser.Files)
    {
        anyFileUploaded = true;
        var path = Path.Combine(PathWhereYouPutUploadedFiles, file.FileName);
        using (var outputFile = File.Create(path))
            file.Data.CopyTo(outputFile);
    }

    if (!anyFileUploaded)
        throw HttpException.BadRequest("You need to post at least one file.");
}
geoperez commented 4 years ago

I updated the Cookbook (https://github.com/unosquare/embedio/wiki/Cookbook#reading-from-a-post-body-as-a-formdata-multipartform-data)

rdeago commented 4 years ago

Thanks a lot @geoperez, your updated snippet looks a lot better. It's async too!

Since the docs have been updated too, I'm closing this. @gnh1201 feel free to reopen, or to create a new issue, if we didn't correctly address your needs.