how to upload a file in webapi


Step 1:- Create a WebApi Project in Visual Studio with Name FileUploadInWebApi. 

Step 2:- Add a Controller name with FileUploading in Controller Folder in your project and paste the following code. 


using System;

using System.IO;

using System.Net.Http;

using System.Threading.Tasks;

using System.Web;

using System.Web.Http;

 

namespace FileUploadInWebAPI.Controllers

{

    public class FileUploadingController : ApiController

    {

        [HttpPost]

        [Route("api/fileuploading/uploadfile")]

        public async Task<string> UploadFile()

        {

            var ctx = HttpContext.Current;

            var root = ctx.Server.MapPath("~/App_Data");

            var provider = new MultipartFormDataStreamProvider(root);

            try

            {

               await Request.Content.ReadAsMultipartAsync(provider);

               foreach(var file in provider.FileData)

                {

                    var name = file.Headers.ContentDisposition.FileName;

                    name = name.Trim('"');

 

                    var localFileName = file.LocalFileName;

                    var filePath = Path.Combine(root, name);

                    File.Move(localFileName, filePath);

                }

            }

            catch (Exception ex)

            {

                return $"Error:{ex.Message}";

            }   

            return "File Uploaded";

        }

    }

}


Step 3:- Run your project and paste this "api/fileuploading/uploadfile" line in Postman url option and select Post Request ,then click on form-data and select file from right, now upload a file. Now click on send.

Step 4:- Check image or file in App_Data folder.   

 




No comments:

Post a Comment