Nancy FX - Post request containing picture - C#

242 Views Asked by At

I am looking for some help using Nancy in C#. First, my goal. My goal is to recover an image contained in a post request from an html form. I thought it would be simple but it's a bit more difficult that I expected ^^. The post request is well sent from the html form and I can read the bytes received with the Nancy module. The problem starts when I try to deserialize the bytes received ! Impossible... In a perfect world, I would like to have the data deserialized in a Image type to work with in my application next.

Here is my html form :

<form action="http://localhost:8080/" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" class="btn btn-default" value="Upload Image" name="submit">
</form>

Here is my C# code :

       Post["/"] = _ =>
        {
            var id = this.Request.Body;
            var length = this.Request.Body.Length;
            var data = new byte[length];
            id.Read(data, 0, (int)length);
            var body = System.Text.Encoding.Default.GetString(data);
            return(10);

        }

Thanks, Mehdi.

1

There are 1 best solutions below

0
Sifiso Shezi On

You need to use Request.Files which is list of all files uploaded. var postedFile = Request.Files.FirstOrDefault(); would return the first file.