scottoffen / grapevine-legacy

Embedding A REST Server In Your Application Should Be Simple
http://scottoffen.github.io/grapevine-legacy/
Apache License 2.0
209 stars 50 forks source link

POST request multipart/form-data #193

Closed 7make closed 5 years ago

7make commented 6 years ago

Have any example to work multipart/form-data from request?

[RestRoute(HttpMethod = HttpMethod.POST, PathInfo = "/in.php")]
public IHttpContext Input(IHttpContext context)
{
    if (!context.Request.HasEntityBody)
    {
        context.Response.SendResponse(Grapevine.Shared.HttpStatusCode.InternalServerError, "sorry");
        return context;
    }
    //parse data from request
}

POST request image

Yangxing1995 commented 5 years ago

Use Http-Multipart-Data-Parser.

            int ChunkSize = 1024;
            try
            {
                using (Stream input = ((HttpRequest)context.Request).Advanced.InputStream)
                {
                    var parser = new HttpMultipartParser.MultipartFormDataParser(input);
                   var task= parser.GetParameterValue("Task");
                   var fullAnswer= parser.GetParameterValue("FullAnswer")

                    // Loop through all the files
                    foreach (HttpMultipartParser.FilePart file in parser.Files)
                    {
                        using (BinaryReader reader = new BinaryReader(file.Data, context.Request.ContentEncoding))
                        {
                            using (BinaryWriter output = new BinaryWriter(File.Open(file.FileName, FileMode.Create)))
                            {
                                byte[] chunk = reader.ReadBytes(ChunkSize);
                                while (chunk.Length > 0)
                                {
                                    output.Write(chunk);
                                    chunk = reader.ReadBytes(ChunkSize);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
            }