nikhil pinto
nikhil pinto

Reputation: 331

Uploading files in a ASP.NET MVC Web api controller

I want to create a WEB API that uploads a file from a given client onto a Azure. For this, I know I can use a class like: MultipartFormDataStreamProvider (not sure if this class works for Azure)

I want this API to be accessible from a variety of applications. For starters a simple .NET application. But my question is can I use this same API to handle file uploads from say an Android application, Windows 8 application, etc?

If this is not possible then do all these applications require a separate API exposed?

My idea of an API is that it can be used across a variety of applications for required functionality. But in this case the classes required to upload the file will restrict its usage.

Upvotes: 4

Views: 3853

Answers (2)

Jayakumar Thangavel
Jayakumar Thangavel

Reputation: 2007

Please find the below sample code to send multiple files to .Net web api via post method

.Net Web API method

   [HttpPost]
    public string SaveImage()
    {
       string uploadedfilelist="";
        if (((IList)HttpContext.Current.Request.Form.AllKeys).Contains("fileModel"))
        {
            var activity = JsonConvert.DeserializeObject<SocialCompanyPost>(HttpContext.Current.Request.Form["fileModel"]);

            var files = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files : null;
            if (files != null && files.Count > 0)
            {
                 for (int i = 0; i < files.Count; i++)
                    {
                        if (files[i].ContentLength > 0)
                        {
                            try
                            {
                                var filepath = HttpContext.Current.Server.MapPath("~/Images/ServiceCenters/" + files[i].FileName);//, ms.ToArray());
                                files[i].SaveAs(filepath);
                                uploadedfilelist += files[i].FileName+",";
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e);
                                throw;
                            }

                        }
                    }
            }
        }
        return uploadedfilelist;
    } 

Client side MVC application post method to call web api post method

    public string UploadImages(ServiceCenterPost socialCompany)
    {
        var url = "api/Images/SaveImage";
        if (socialCompany.ThumbnailUrlFileUpload.Count() > 0)
        {
            var fullURL = ConfigurationManager.AppSettings["ServiceApi"] + url;
            HttpClient client = new HttpClient();
            MultipartFormDataContent form = new MultipartFormDataContent();
            var stringContent = new StringContent(JsonConvert.SerializeObject(new SocialCompanyAdmin { CompanyCode = socialCompany.CompanyCode }));
            stringContent.Headers.Add("Content-Disposition", "form-data; name=\"fileModel\"");
            form.Add(stringContent, "json");
            //loop each files from file upload control
            foreach (var file in socialCompany.ThumbnailUrlFileUpload)
            {
                if (file != null && file.ContentLength > 0)
                {                        
                    var streamContent = new StreamContent(file.InputStream);
                    streamContent.Headers.Add("Content-Type", "application/octet-stream");
                    streamContent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"" + Path.GetFileName(file.FileName) + "\"");
                    form.Add(streamContent, "file", Path.GetFileName(file.FileName));
                }
            }
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            client.DefaultRequestHeaders.Add("Accept-Language", Language);
            var response = client.PostAsync(fullURL, form).Result;
            if (response.IsSuccessStatusCode)
            {
                    string modelObject = response.Content.ReadAsStringAsync().Result;
                    return JsonConvert.DeserializeObject<string>(modelObject);

            }              
        }
        return null;
    } 

Upvotes: 3

Nilesh Gajare
Nilesh Gajare

Reputation: 6398

Web Api code to upload image

[System.Web.Http.AcceptVerbs("POST")]
        public async Task<object> AddAttachment()
        {
            if (!Request.Content.IsMimeMultipartContent("form-data"))
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
            }

            NamedMultipartFormDataStreamProvider streamProvider = new NamedMultipartFormDataStreamProvider(
                HttpContext.Current.Server.MapPath("~/App_Data/"));

            await Request.Content.ReadAsMultipartAsync(streamProvider);
            string path = streamProvider.FileData.Select(entry => entry.LocalFileName).First();
            byte[] imgdata = System.IO.File.ReadAllBytes(path);

            return new
            {
                FileNames = streamProvider.FileData.Select(entry => entry.LocalFileName),

            };
        }

Upvotes: 1

Related Questions