Sunday 26 January 2020

File Upload in Angular

File Upload in Angular
step :1 create the component ng g c fileUpload

file-upload.component.html

<div class="container">
  <div class="row">
      <div class="col-md-6 offset col-md-3">
          <h3>Choose File</h3>
          <div class="form-group">
              <input type="file" name="image" (change)="fileProgress($event)" />
          </div>
          <div *ngIf="fileUploadProgress">
              Upload progress: {{ fileUploadProgress }}
          </div>
          <div class="image-preview mb-3" *ngIf="previewUrl">
              <img [src]="previewUrl" height="300" />
          </div>

          <div class="mb-3" *ngIf="uploadedFilePath">

              {{uploadedFilePath}}
          </div>

          <div class="form-group">

              <button class="btn btn-primary"  (click)="onSubmit()">Submit</button>
          </div>
      </div>
  </div>

</div>


file-upload.component.ts


import { Component, OnInit } from "@angular/core";

import { HttpClient } from "@angular/common/http";
import { EmployeeService } from '../employee.service';

@Component({

  selector: "app-file-upload",
  templateUrl: "./file-upload.component.html",
  styleUrls: ["./file-upload.component.scss"]
})
export class FileUploadComponent implements OnInit {
  fileData: File = null;
  previewUrl: any = null;
  fileUploadProgress: string = null;
  uploadedFilePath: string = null;
  constructor(private employeeService: EmployeeService, private http: HttpClient) {}

  fileProgress(fileInput: any) {

    this.fileData = <File>fileInput.target.files[0];
    this.preview();
  }
  ngOnInit() {}
  preview() {
    // Show preview
    var mimeType = this.fileData.type;
    if (mimeType.match(/image\/*/) == null) {
      return;
    }
    var reader = new FileReader();
    reader.readAsDataURL(this.fileData);
    reader.onload = _event => {
      this.previewUrl = reader.result;
    };
  }

  onSubmit() {

    this.employeeService.UploadFile(this.fileData).subscribe(res => {
      console.log(res);
      this.uploadedFilePath = res.Message;
      alert(res + "SUCCESS !!");
    }); 
  }

}


Step :2

web API controller :FileUploadController.cs

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 EmployeeAPI.Controllers
{
    public class FileuploadController : ApiController
    {
        [HttpPost]      
        public async Task<HttpResponseMessage> PostUserImage()
        {
            Dictionary<string, object> dict = new Dictionary<string, object>();
            string message1 = string.Empty;
            try
            {

                var httpRequest = HttpContext.Current.Request;
                
                foreach (string file in httpRequest.Files)
                {
                    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);

                    var postedFile = httpRequest.Files[file];
                    
                    if (postedFile != null && postedFile.ContentLength > 0)
                    {

                        int MaxContentLength = 1024 * 1024 * 1; //Size = 1 MB

                        IList<string> AllowedFileExtensions = new List<string> { ".jpg",".jpeg", ".gif", ".png" };
                        var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
                        var extension = ext.ToLower();
                        if (!AllowedFileExtensions.Contains(extension))
                        {
                            var message = string.Format("Please Upload image of type .jpg,.gif,.png.");
                            dict.Add("error", message);
                            return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
                        }
                        else if (postedFile.ContentLength > MaxContentLength)
                        {

                            var message = string.Format("Please Upload a file upto 1 mb.");
                            dict.Add("error", message);
                            return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
                        }
                        else
                        {
                            //  where you want to attach your imageurl
                            //if needed write the code to update the table
                            string fname = postedFile.FileName.Replace(extension, DateTime.Now.ToString("ddMMyyyyHHmmss") + extension);
                            var filePath = HttpContext.Current.Server.MapPath("~/Images/" + fname);
                            //Userimage myfolder name where i want to save my image
                            postedFile.SaveAs(filePath);
                            message1 = @"http://localhost:60044/Images/" + fname;
                        }
                    } 
                  //  var message1 = @"http://localhost:60044/Images/" + postedFile.FileName;// string.Format("Image Updated Successfully.");
                    return Request.CreateErrorResponse(HttpStatusCode.Created, message1); ;
                }
                var res = string.Format("Please Upload a image.");
                dict.Add("error", res);
                return Request.CreateResponse(HttpStatusCode.NotFound, dict);
            }
            catch (Exception ex)
            {
                var res = string.Format("some Message");
                dict.Add("error", res);
                return Request.CreateResponse(HttpStatusCode.NotFound, dict);
            }
        }
    }
}

Output :

API Created url :
http://localhost:60044/Images/lion-wild-africa-african26012020094056.jpg




No comments:

Post a Comment

Top Agile Interview Questions & Answers

Top Agile Interview Questions & Answers 1. What is Agile Testing? The first question of agile interview question tests your k...