Restsharp posting file and data with Stream - Binary stream - Post call

Restsharp posting  file and data with Stream - Binary stream - Post call

WebApiConfig.cs



In order to add support for multipart/form-data we need to add below line to webapi.config

config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace RestSharpEx
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();
            config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}



MyApiController.cs


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using Newtonsoft.Json;
using RestSharpEx.Models;

public class MyApiController : ApiController
    {
[HttpPost, Route("BulkUploadFileWithStream")]
        public void BulkUploadFileWithStream(FileUploadModel model)
        {
            HttpResponseMessage result = null;
            var httpRequest = HttpContext.Current.Request;
            //Access your variable using
            var me = JsonConvert.DeserializeObject<FileUploadModel>((HttpContext.Current.Request.Params["model"]).ToString());
            if (httpRequest.Files.Count > 0)
            {
                var docfiles = new List<string>();
                foreach (string file in httpRequest.Files)
                {
                    var postedFile = httpRequest.Files[file];
                    var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
                    #region Reading to binary
                    byte[] data;
                    using (BinaryReader reader = new BinaryReader(postedFile.InputStream))
                    {
                        data = reader.ReadBytes((int)postedFile.InputStream.Length);
                    }
                    //ConvertCSVToTable(model, new MemoryStream(data));
                    #endregion

                    postedFile.SaveAs(filePath);
                    docfiles.Add(filePath);
                }
                result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
            }
        }

}

HomeController.cs


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using RestSharp;
using RestSharpEx.Models;

namespace RestSharpEx.Controllers
{
    public class HomeController : Controller
    {
[HttpPost]
        public ActionResult postWithFileWithStream(FileUploadModel model)
        {
            if (Request.Files.Count > 0)
            {
                var file = Request.Files[0];

                if (file != null && file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    //var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
                    // file.SaveAs(path);
                    #region Reading to binary
                    byte[] data;
                    using (BinaryReader reader = new BinaryReader(file.InputStream))
                    {
                        data = reader.ReadBytes((int)file.InputStream.Length);
                    }
                    //ConvertCSVToTable(model, new MemoryStream(data));
                    #endregion
                    var apiUrl = @"http://localhost:8076/api/MyApi/BulkUploadFile";
                    var client = new RestClient(apiUrl);
                    //if (!string.IsNullOrWhiteSpace(userName))
                    //{
                    //    client.Authenticator = new HttpBasicAuthenticator(userName, password);
                    //}
                    client.ClearHandlers();
                    //var jsonDeserializer = new JsonDeserializer();
                    //client.AddHandler("application/json", jsonDeserializer);
                    var request = new RestRequest(Method.POST);
                    request.AddHeader("Accept", "application/json");
                    request.Parameters.Clear();
                    request.AddParameter("model", JsonConvert.SerializeObject(model));
                    request.AddHeader("Content-Type", "multipart/form-data");
                    Stream newStream = new MemoryStream(data);
                    request.Files.Add(new FileParameter
                    {
                        Name = "file",
                        Writer = (s) =>
                        {
                            newStream.CopyTo(s);
                        },
                        FileName = fileName,
                        // ContentType = "text/csv",
                        ContentLength = newStream.Length
                    });
                    var result = client.Execute(request).Content;
                    var finalResult = JsonConvert.DeserializeObject<FileUploadModel>(result);
                }

            }
            return View(model);
        }
}
}

Below line code is important here we are just saving InputStream from File into bytes. Which can be used further as many times as we want using new MemoryStream(data).

                    #region Reading to binary
                    byte[] data;
                    using (BinaryReader reader = new BinaryReader(postedFile.InputStream))
                    {
                        data = reader.ReadBytes((int)postedFile.InputStream.Length);
                    }
                    //ConvertCSVToTable(model, new MemoryStream(data));
                    #endregion

And also we need to add file manually so that  we have the control to add a stream to to the file.

request.Files.Add(new FileParameter
                    {
                        Name = "file",
                        Writer = (s) =>
                        {
                            newStream.CopyTo(s);
                        },
                        FileName = fileName,
                        // ContentType = "text/csv",
                        ContentLength = newStream.Length
                    });



View.cshtml


@model RestSharpEx.Models.FileUploadModel

@{
    ViewBag.Title = "PostWithFile";
}

<h2>PostWithFile</h2>


@*@using (Html.BeginForm())*@
    @using (Html.BeginForm("PostWithFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>FileUploadModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.FileId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FileId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FileId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.FileDescription, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FileDescription, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FileDescription, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.FileDescription, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <input type="file" name="file" />
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Note : We need to use     @using (Html.BeginForm("PostWithFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))

in begin form in order to send to model with file upload data.

Share on Google Plus

About myzingonline

Myzingonline is all about zing to share experience, knowledge, likes, dislikes and ideas of a person to the world.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment