File Upload From Request Header In Postman

In This Article, I Will Show You How To Upload A File Using Request Header In Postman

Here, I Will Explain How To Make a Web API To Upload Documents, PPT, Images, multipart/form-data, etc. on Server or  Save On Local folder.

Now Let’s Start

  • Create an Empty Web API
  • Create an API Controller.

Now Put The Bellow  Code Into The Controller

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using InvoiceWebApi.Model;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace ImageWebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UploadController : ControllerBase
    {
        private IHostingEnvironment _environment;
        public UploadController(IHostingEnvironment environment)
        {
            _environment = environment;
        }
        [HttpPost, DisableRequestSizeLimit]
        public IActionResult UploadFile()
        {
            try
            {
                var files = Request.Form.Files;
                var folderName = Path.Combine("Upload");
                string webRootPath = _environment.WebRootPath;
                string newPath = Path.Combine(webRootPath, folderName);
                if (!Directory.Exists(newPath))
                {
                    Directory.CreateDirectory(newPath);
                }
                if (files.Any(f => f.Length == 0))
                {
                    return BadRequest();
                }

                foreach (var file in files)
                {
                    
                    var fileName = DateTime.Now.Ticks+ ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                    var fullPath = Path.Combine(newPath,fileName);

                    using (var stream = new FileStream(fullPath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                    }
                }

                return Ok("");
            }
            catch (Exception ex)
            {
                return StatusCode(500, "Internal server error");
            }
        }
    }
}

Now Run The Project And Open The Postman And Upload Files.

How To Upload File 

1.Open The Postman And Enter The URL: http://localhost:64696/api/Upload
2.Select The Post Method
3.Now In The Body Tab
->Click On Form-Data Radio Button
->Add a File Key Name And Select The File Instead Of Text.
->And Select Choose Files And Select Multiple Files Which You Want To Upload

So, Here It Will Create Upload Folder If It's Not Exist.
Else It Will Be Uploaded To The Same folder.

Submit a Comment

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

Footer Logo

Subscribe

Select Categories