Translate

Home > November 2020

November 2020

AngularJs ASP.NET WepApi File Upload

Sunday, November 1, 2020 Category : , 0

 AngularJs Code:


 var formData = new FormData();
      
        formData.append('files', data);
        formData.append('fileName', data.name);

        return $http({
            url: _urlBase + 'api/app/CustomerExcelUpload',
            method: 'POST',
            //data: JSON.stringify(data),
            processData: false,
            contentType: false,
            data: (formData),
            headers: { 'content-type': undefined, 'Authorization': username + ':' + password }
                    //, transformRequest: angular.identity
            });



ASP.NET WebApi (4.5)


  [HttpPost]
        [Route("api/app/CustomerExcelUpload")]
        public async Task<IHttpActionResult> CustomerExcelUpload()
        {
            //HttpResponseMessage result = null;
            ResponseObj responsobj = new ResponseObj();
            responsobj.COUNT = 0;
            responsobj.CODE = 0;

            try
            {
                

                if (HttpContext.Current.Request.Files.AllKeys.Any())
                {
                    // Get the uploaded image from the Files collection
                    var httpPostedFile = HttpContext.Current.Request.Files["files"];
                    var httpFileName = HttpContext.Current.Request.Form["fileName"];

                    if (httpPostedFile != null)
                    {
                        // Validate the uploaded image(optional)

                        // Get the complete file path
                        var fileSavePath = System.IO.Path.Combine(HttpContext.Current.Server.MapPath("~/upload_doc"), httpPostedFile.FileName);

                        // Save the uploaded file to "UploadedFiles" folder
                        httpPostedFile.SaveAs(fileSavePath);
                    }
                }

                responsobj.Message = "OK";
                responsobj.Success = true;
                responsobj.CODE = 0;
                return Content(HttpStatusCode.OK, responsobj);

            }
            catch (Exception ex)
            {
                Log.Debug("Bad Request");
                responsobj.Message = ex.Message;
                responsobj.Success = false;
                responsobj.CODE = 2;
                return Content(HttpStatusCode.OK, responsobj);

            }
        }



<system.web>
  <httpRuntime executionTimeout="240000" maxRequestLength="2147483647" />
</system.web>

<security>
  <requestFiltering>
    <requestLimits maxAllowedContentLength="4294967295"/>
  </requestFiltering>
</security>

Powered by Blogger.