Upload File with Other Body Parameters in ASP.Net Web API

n

n
nI recently had a requirement in an angular application I was writing for a client to upload image with other body parameters via ASP.Net API. It look pretty easy to me at first, but I later realize that it’s a little bit tricky.
n
nIn this article am going to walk you through how I finally got it done.
nnn
nnn
n

nUpload Only File Without Parameter

nLet’s see how it can be done if we want to upload an image without any additional form information in web api,
n
n

nWeb API Controller

nThe code below is all we need to get an image from an incoming request from the API consumer.
n
n

        [HttpPost]n        public HttpResponseMessage UploadImage()n        {n            var exMessage = string.Empty;n            tryn            {n                string uploadPath = "~/content/upload";n                HttpPostedFile file = null;n                if (HttpContext.Current.Request.Files.Count > 0)n                {n                    file = HttpContext.Current.Request.Files.Get("file");n                }n                // Check if we have a filen                if (null == file)n                    return Request.CreateResponse(HttpStatusCode.BadRequest, newn                    {n                        error = true,n                        message = "Image file not found"n                    });nn                // Make sure the file has contentn                if (!(file.ContentLength > 0))n                    return Request.CreateResponse(HttpStatusCode.BadRequest, newn                    {n                        error = true,n                        message = "Image file not found"n                    });nn                if (!Directory.Exists(HttpContext.Current.Server.MapPath(uploadPath)))n                {n                    // If it doesn't exist, create the directoryn                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath(uploadPath));n                }nn                //Upload Filen                file.SaveAs(HttpContext.Current.Server.MapPath($"{uploadPath}/{file.FileName}"));nn            }n            catch (Exception ex)n            {n                exMessage = ex.Message;n            }n            return Request.CreateResponse(HttpStatusCode.BadRequest, new { error = true, message = exMessage == string.Empty ? "An unknown error occured" : exMessage });n        }nn

n
nIn the code above all I have done is to check if we have file in the request, and if exist check if there anyone with the key of file.
n
n
n

nAngular Service Method

nWe only need the below code in the angular app that we send the image to our API:
n
n

    uploadImage(url: string, params: any, file: File) {n        return new Promise((resolve, reject) => {n            var formData: any = new FormData();n            var xhr = new XMLHttpRequest();n            formData.append("file", file, file.name);n           n            xhr.onreadystatechange = function () {n                if (xhr.readyState == 4) {n                    if (xhr.status == 201) {n                        resolve(JSON.parse(xhr.response));nn                    } else {n                        reject(JSON.parse(xhr.response));n                    }n                }n            }n            xhr.open("POST", url, true);n            xhr.send(formData);n        });n    }n

n
n

nUpload with more parameters

nAs you can see that what have done so far is fairly straight forward. But what if we want to send some more fields with the image – say for example, we want to upload a product image and we need to send the productId and description in the request.
nnnn
nWhat I have to do to accomplish this task is to modify the uploadImage method in the angular service by adding this two lines:
nnn
nnn
n

formData.append("productId", params.productId);nformData.append("description", params.description);n

n
nNow the uploadImage method should look like this:
n
n

    n    uploadImage(url: string, params: any, file: File) {n        return new Promise((resolve, reject) => {n            var formData: any = new FormData();n            var xhr = new XMLHttpRequest();n            formData.append("file", file, file.name);n            n            formData.append("productId", params.productId);n            formData.append("description", params.description);nn            xhr.onreadystatechange = function () {n                if (xhr.readyState == 4) {n                    if (xhr.status == 201) {n                        resolve(JSON.parse(xhr.response));nn                    } else {n                        reject(JSON.parse(xhr.response));n                    }n                }n            }n            xhr.open("POST", url, true);n            xhr.send(formData);n        });n    }n

nAs you can see, I have added productId and description as part of the request paramters.
n
nThose parameters now will be available as part of the incoming request in the web api.
n

n
Web API Modified code

nWe can now get the additional parameters by adding this to our api method:
n
n

int productId = int.Parse(HttpContext.Current.Request.Params.Get("productId"));nstring description = HttpContext.Current.Request.Params.Get("description")n

nThe full code will now look like this:nn
n

        [HttpPost]n        public HttpResponseMessage UploadImage()n        {n            var exMessage = string.Empty;n            tryn            {n                string uploadPath = "~/content/upload";n                HttpPostedFile file = null;n                if (HttpContext.Current.Request.Files.Count > 0)n                {n                    file = HttpContext.Current.Request.Files.Get("file");n                }n                // Check if we have a filen                if (null == file)n                    return Request.CreateResponse(HttpStatusCode.BadRequest, newn                    {n                        error = true,n                        message = "Image file not found"n                    });nn                // Make sure the file has contentn                if (!(file.ContentLength > 0))n                    return Request.CreateResponse(HttpStatusCode.BadRequest, newn                    {n                        error = true,n                        message = "Image file not found"n                    });nn                int productId = int.Parse(HttpContext.Current.Request.Params.Get("productId"));n                string description = HttpContext.Current.Request.Params.Get("description")nn                if (!Directory.Exists(HttpContext.Current.Server.MapPath(uploadPath)))n                {n                    // If it doesn't exist, create the directoryn                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath(uploadPath));n                }nn                //Upload Filen                file.SaveAs(HttpContext.Current.Server.MapPath($"{uploadPath}/{file.FileName}"));nn            }n            catch (Exception ex)n            {n                exMessage = ex.Message;n            }n            return Request.CreateResponse(HttpStatusCode.BadRequest, new { error = true, message = exMessage == string.Empty ? "An unknown error occured" : exMessage });n        }nn

nThat is all we have to do. Let us know if you have a better way of doing this.nnI hope this helps. Thanks for your time.nn
n

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top