Angular

Drag & Drop Image Upload In Angular 10 With .NET Core

In this article, we will learn how to implement drag and drop image upload in Angular 10 with .Net Core.

For better user experience drag and drop image upload is interesting feature nowadays. This article will help you to implement drag and drop file upload with image preview.

Prerequisites:

  • Basic knowledge of Angular and .NET Core
  • Code editor like Visual Studio Code and Visual Studio

Create .NET Core API

Let’s first create an API with .NET Core to upload an image.

Now create and open the UploadController.cs file and add the code in it.

using System;
using System.IO;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc;

namespace Drag_Drop_File_Upload.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UploadController : ControllerBase
    {
        [HttpPost]
        public IActionResult UploadFile()
        {
            try
            {
                if (Request.Form.Files.Count == 1)
                {
                    var file = Request.Form.Files[0];
                    string folderName = "Upload";
                    string newPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", folderName);
                    if (!Directory.Exists(newPath))
                    {
                        Directory.CreateDirectory(newPath);
                    }
                    if (file.Length > 0)
                    {
                        string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                        string fullPath = Path.Combine(newPath, fileName);
                        using (var stream = new FileStream(fullPath, FileMode.Create))
                        {
                            file.CopyTo(stream);
                        }
                    }
                    return Ok();
                }
                else
                {
                    return NotFound();
                }
            }
            catch (Exception)
            {
                return BadRequest();
            }
        }
    }
}

Now open the Startup.cs file and add the code in it as given below to allow CORS requests from any origin. The methods we are interested in are called on line number 22 and 3741.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Drag_Drop_File_Upload
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddCors();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            // global cors policy
            app.UseCors(x => x
                .AllowAnyMethod()
                .AllowAnyHeader()
                .SetIsOriginAllowed(origin => true));

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

Drag & Drop Image Upload In Angular 10

Now let’s follow the steps given below to implement drag and drop image upload feature in Angular project.

Let’s first create a new interface by typing the following command in the VSCode terminal.

ng g i HandleFile

Open the handle-file.ts file and add the code in it.

import { SafeUrl } from '@angular/platform-browser';

export interface HandleFile {
    file: File;
    url: SafeUrl;
}

Now create a new directive by typing the following command in the VSCode terminal and add the code in it.

ng g d DragDrop

Open the drag-drop.directive.ts file and add the code in it.

import { Directive, Output, EventEmitter, HostBinding, HostListener } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { HandleFile } from './handle-file';

@Directive({
  selector: '[appDragDrop]'
})
export class DragDropDirective {
  @HostBinding('style.background') public bg = '#000000';
  @Output('file') file: EventEmitter<HandleFile> = new EventEmitter();
  constructor(private sanitizer: DomSanitizer) { }
  @HostListener('dragover', ['$event']) public onDragOver(e: DragEvent) {
    e.preventDefault();
    e.stopPropagation();
    this.bg = '#999';
  }
  @HostListener('dragleave', ['$event']) public onDragLeave(e: DragEvent) {
    e.preventDefault();
    e.stopPropagation();
    this.bg = '#000000';
  }
  @HostListener('drop', ['$event']) public onDrop(e: DragEvent) {
    e.preventDefault();
    e.stopPropagation();
    this.bg = '#000000';
    const droppedFile = e.dataTransfer.files[0];
    const url = this.sanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(droppedFile));
    let handleFile: HandleFile = {
      file: droppedFile,
      url: url
    };
    this.file.emit(handleFile);
  }
}

In DragDropDirective we used dragover, dragleave and drop events with the help of @HostListner. And we used DomSanitizer to obtain files URL to show them in <img> tag.

Open the app.module.ts file and add the code in it.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { DragDropDirective } from './drag-drop.directive';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
    DragDropDirective
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Open the app.component.html file and add the code in it.

<div appDragDrop (file)="dragDropFile($event)" style="height: 300px; text-align: center;">
    <h1 style="color: white;">Drag & Drop Image here (jpeg/jpg/png)</h1>
    <div *ngIf="droppedFile != null">
        <img [src]="droppedFile.url" height="200" width="200" />
        <br>
        <button (click)="uploadFile()">Upload</button>
    </div>
</div>

Open the app.component.ts file and add the code in it.

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HandleFile } from './handle-file';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Drag-Drop-File-Upload';
  droppedFile: HandleFile;
  formData = new FormData();

  constructor(private http: HttpClient) { }

  dragDropFile(file: HandleFile) {
    if (file.file.type == "image/jpeg" || file.file.type == "image/png") {
      this.droppedFile = file;
    }
  }
  uploadFile() {
    this.formData.append('photo', this.droppedFile.file);
    return this.http.post('https://localhost:44325/api/Upload', this.formData).subscribe(      
      (response) => {        
        alert('File Uploaded Successfully')
      },
      (error) => {        
        alert('Something Went Wrong !!!')
      }
    );
  }
}

Output:

Please give your valuable feedback and if you have any questions or issues about this article, please let me know.

Also, check Hide Eye Icon From Password Input In MS Edge And IE 10 Using CSS

Yasin Panwala

Yasin Panwala is a Web Developer and Author at TheCodeHubs. He has experience in Web Developing and Designing and also in Writing. He has got his skills in working on technologies like .NET Core, ADO.NET, AJAX, Angular, AngularJS, ASP.NET, ASP.NET MVC, Bootstrap, C#, CSS, Entity Framework, Express.js, GraphQL, HTML, JavaScript, JQuery, JSON, LINQ, Microsoft Office, MongoDB, MySQL, Node.js, PostgreSQL, SQL, SQL Server, TypeORM, TypeScript, Visual Basic .NET, Web API. He also got his skills in working with different integration and some known versioning tools. He is always ready to learn new things and he always tries his best on tasks that are assigned to him and gives the best possible outputs.

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago