Thursday, 19 January 2017

Various ways to upload a file and save it in server using WEBAPI controller

In this post we are going to see how to create a web api controller for upload and save a file, in api normally data is send as multipart form data , so inside the post action we are going to define the logic, it can be done in various ways.

First we have to create a actionFilter attribute, which can be used to filter the request based on whether it is Mime multipart content or not IsMimeMultipartContent.

    public class CheckMimeMultiPart : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (!actionContext.Request.Content.IsMimeMultipartContent())
            {
                throw new                                   
                HttpResponseException(System.Net.HttpStatusCode.UnsupportedMediaType);
            }
        }

    }

Then now we are going to do core logic.

        [CheckMimeMultiPart]
        public async Task<FilePostResult> Post()
        {
            try
            {
                var path = HttpContext.Current.Server.MapPath("~/img");
                var streamprovider = new MultipartFormStreamProvider(path);
                await Request.Content.ReadAsMultipartAsync(streamprovider);


                var localfilename = streamprovider.FileData.Select(x => x.LocalFileName)
                                   .FirstOrDefault();

                var fileinfo = new FileInfo(localfilename);
                var response = new FilePostResult();

                response.FileName = fileinfo.Name;
                response.Size = fileinfo.Length;
                response.Url = Request.RequestUri.GetLeftPart(UriPartial.Authority) 
                                   +"/img/" + response.FileName; ;

                return response;                               
                 
            }catch(Exception ex)
            {
                return new FilePostResult()
                {
                    FileName = "",
                    Size =0,
                    Url = Request.RequestUri.GetLeftPart(UriPartial.Authority)
                };
            }

        }

    }

sometimes In the above code  await Request.Content.ReadAsMultipartAsync(streamprovider);
you may get a error in this line ,, then use below code instead of that


                var streamProvider = await Request.Content.ReadAsMultipartAsync(); 
                foreach (var file in streamProvider.Contents)
                {
                    var Filename = file.Headers.ContentDisposition.FileName.Trim('\"');
                    var imageStream = await file.ReadAsStreamAsync();

                }



Now you have to save this imagestream as File , using FileStream.


From the above code you can learn how to create the a web api controller for upload and save a file.

No comments:

Post a Comment