Web
Analytics
web api 2 file upload asp.net mvc | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

Step 1: Create a empty MVC project with  MVC and Web API checkbox selected.

webapifileupload1

webapifileupload2




Step 2: Add WebAPI2 Controller in controller folder.

webapifileupload3

Step4: Write Following Code in WEBAPI Controller.

 

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace WEBAPIVideoDEMO.Controllers
{
    public class fileuploadController : ApiController
    {
        public Task<HttpResponseMessage> Post()
        {
            List<string> savedFilePath = new List<string>();
            // Check if the request contains multipart/form-data
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            //Get the path of folder where we want to upload all files.
            string rootPath = HttpContext.Current.Server.MapPath("~/documents");
            var provider = new MultipartFileStreamProvider(rootPath);
            // Read the form data.
            //If any error(Cancelled or any fault) occurred during file read , return internal server error
            var task = Request.Content.ReadAsMultipartAsync(provider).
                ContinueWith<HttpResponseMessage>(t =>
                {
                    if (t.IsCanceled || t.IsFaulted)
                    {
                        Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
                    }
                    foreach (MultipartFileData dataitem in provider.FileData)
                    {
                        try
                        {
                            //Replace / from file name
                            string name = dataitem.Headers.ContentDisposition.FileName.Replace("\"", "");
                            //Create New file name using GUID to prevent duplicate file name
                            string newFileName = Guid.NewGuid() + Path.GetExtension(name);
                            //Move file from current location to target folder.
                            File.Move(dataitem.LocalFileName, Path.Combine(rootPath, newFileName));

                          
                        }
                        catch (Exception ex)
                        {
                            string message = ex.Message;
                        }
                    }

                    return Request.CreateResponse(HttpStatusCode.Created, savedFilePath);
                });
            return task;
        }
    }
}

Step 5: Create new Controller and write following code.

 

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

namespace WEBAPIVideoDEMO.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
       
        public ActionResult fileupload()
        {
            return View();
        }
    }
}





 

Step 6:Add View in fileupload action and add following code.

 

@{
    ViewBag.Title = "fileupload";
}
<script src="~/Scripts/jquery-1.10.2.js"></script>
<h2>fileupload</h2>
<div>
   
    <div class="form-group">
        <input type="file" id="myfile" />
    </div>
    <input id="btn1" class="btn btn-default" type="button" value="Upload" />
</div>


    <script>
        $(document).ready(function () {
            $('#btn1').click(function () {
                if ($('#myfile').val() == '') {
                    alert('Please select file');
                    return;
                }

                var formData = new FormData();
                var file = $('#myfile')[0];
                formData.append('file', file.files[0]);
                $.ajax({
                    url: '/api/fileUpload',
                    type: 'POST',
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function (d) {
                       alert('file is uploaded successfully')
                    },
                    error: function () {
                        alert('Some thing went wrong');
                    }
                });
            });
        });
    </script>

asp.net core 2.0 with angular online training