Search code examples
angularfile-uploadasp.net-coreasp.net-apicontroller

How to pass image from Angular(2/4) to in ASP.NET Core WebAPI server folder


My file is in the following format in Angular end:

let fi = this.fileInput.nativeElement;
let fileToUpload = fi.files[0];

let input = new FormData();
input.append("file", fileToUpload);

return this.http.post(uploadUrl, input);

And my API in ASP.NET CORE is:

[HttpPost]
public IActionResult Post([FromBody]JObject objData)
{
    dynamic jsonData = objData;
    JObject FileJson = jsonData.jsonFile; // JSON File

    // Please suggest how to store the file in Folder
}

Thanks in advance


Solution

  • I have figured it out. So I am posting the answer so that it can help out others.

    This is my complete code in ASP.NET Core API Controller :

    public class FileUploadController : Controller
    {
        private IHostingEnvironment _env;
        public FileUploadController(IHostingEnvironment env)
        {
            _env = env;
        }
        [HttpPost]
        public IActionResult Upload(IFormFile file)
        {
    
            long size = 0;
    
                var filename = ContentDispositionHeaderValue
                                .Parse(file.ContentDisposition)
                                .FileName
                                .Trim('"');
    
    
            var webRoot = _env.WebRootPath;
    
            var filePath = webRoot + "/Uploads" + $@"/{ filename}";
    
            bool fileExists = (System.IO.File.Exists(filePath) ? true : false);
    
            if (fileExists)
            {
                Random random = new Random();
                var randomNum = random.Next(99999);
                filename = randomNum +filename;
                filePath = webRoot + "/Uploads" + $@"/{ filename}";
            }
            size += file.Length;
                using (FileStream fs = System.IO.File.Create(filePath))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
            return Ok(filename);
        }
    }
    

    This in my Image Upload service in Angular:

    export class UploadService {
       constructor(private http: Http) { }
    
       public upload = function (fileToUpload: any, uploadUrl) {
    
         let input = new FormData();
         input.append("file", fileToUpload);
    
         return this.http.post(uploadUrl, input);
       }
    } 
    

    This is my documentSubmit function in Angular component :

    import { UploadService } from './Upload.service';

    constructor(private http: Http,private uploadService: UploadService) { }

    @ViewChild("fileInput") fileInput;

    onDocumentSubmit = function () {
    
      let fi = this.fileInput.nativeElement;
    
      if (fi.files && fi.files[0]) {
    
      let fileToUpload = fi.files[0];
    
      this.uploadService.upload(fileToUpload, ConstantComponent.url + "/FileUpload")
        .subscribe(data => {
    
          let documentDetails = {
            PodId: this.podId,
            DocumentName: fileToUpload.name,
            DocumentPath: ConstantComponent.port + "/Uploads/" + data._body,
          }
          this.http.post(ConstantComponent.url + "/DocumentManagerAPI/Add", documentDetails, options)
            .map((res: Response) => res.json()).subscribe(
            data => {
              console.log("success")
    
            }, error => {
              console.log("error")
    
            });
        });
      }
    }
    

    And this is my File Input HTML :

    <input #fileInput type="file" name="document" [(ngModel)]="document" />