upload file Archives - Learn Smart Coding https://blogs.learnsmartcoding.com/tag/upload-file/ Everyone can code! Sun, 05 Apr 2020 16:29:57 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.2 209870635 How to upload a file from Angular 9 with .NET Core Web API https://blogs.learnsmartcoding.com/2020/04/05/how-to-upload-a-file-from-angular-9-with-net-core-web-api/ https://blogs.learnsmartcoding.com/2020/04/05/how-to-upload-a-file-from-angular-9-with-net-core-web-api/#comments Sun, 05 Apr 2020 16:29:57 +0000 https://karthiktechblog.com/?p=451 In this post, I will show how to upload a file from Angular 9 with .NET Core. Uploading a file is the process of uploading a file from the user’s system to a hosted web application server. You may choose to store the file in the web server’s local disc or in the database. It […]

The post How to upload a file from Angular 9 with .NET Core Web API appeared first on Learn Smart Coding.

]]>
In this post, I will show how to upload a file from Angular 9 with .NET Core.

Uploading a file is the process of uploading a file from the user’s system to a hosted web application server. You may choose to store the file in the web server’s local disc or in the database.

It is easy to upload one or more files from Angular 9 with .NET Core 2.2, 3.1, or above versions.

In this post, I will show what code is needed in the Angular component and service to upload a file to the server-side using .NET Core 3.1. I will also cover some basic client-side validation from Angular 9.

Upload a file from Angular

Video Demo

Service

import { HttpClient } from '@angular/common/http';
import { CONFIG } from 'src/app/config';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class UploadService {
    private apiUrl: string;

    constructor(private http: HttpClient) {
        this.apiUrl = CONFIG.coreAPIUrl;
    }

    public uploadFile(file: FormData): Observable {
        const url = `${this.apiUrl}/${CONFIG.apiEndpoints.encode.fileToBase64}`;
        return this.http.post(url, file);
    }
}

In this service, we have a HttpPost method in which we post the file to the server to upload the local file. This is done using FormData as a parameter.

How to upload a file from Angular 9 with .NET Core

Component

import { Component, OnInit, ChangeDetectionStrategy, ViewChild, ElementRef } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { LoadingService } from '@control-tower/lib';
import { Subject } from 'rxjs';
import { FileContentModel } from '../model/file-content-model';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
  selector: 'app-upload',
  templateUrl: './upload.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [LoadingService]
})
export class UploadComponent implements OnInit {

  @ViewChild('fileInput', {static: false})
  myFileInput: ElementRef;
  public fileContentModel: FileContentModel;
  public form: FormGroup;
  public errors: string[] = [];
  private destroy: Subject = new Subject();

  constructor(
    private uploadService: UploadService
  ) { }

  public ngOnInit() {
    this.form = this.buildForm();
  }

  private buildForm(): FormGroup {
    return new FormGroup({
      fileContact: new FormControl('', [Validators.required])
    });
  }

  public Submit(files: File[]): void {
    this.handleFileInput(files);
  }

  public handleFileInput(files: File[]): void {

    if (this.form.valid && files[0].name.split('.').pop() === 'excel') {
      const formData = new FormData();

      Array.from(files).forEach(f => formData.append('file', f));

      this.uploadService.uploadPdfToGetBase64(formData).subscribe(
        (res: any) => {
          this.myFileInput.nativeElement.value = '';
        },
        (errorRes: HttpErrorResponse) => {
          alert('error occured');
          this.form.reset();
          this.myFileInput.nativeElement.value = '';
        }
      );
    } else {
      alert('Invalid file selected. Only excel is allowed');
    }
  }

}

Explanation

In this component, we consume UploadService in the constructor and then invoke the upload method to send the file to the server.

We create an instance of FormData and append the files to it as KeyValue pair.

Once the response is received, we could display success message or in case of error, we display appropriate error message.

In this example, I have applied a validation to check only excel files can be selected. Any other files selected will show an error message to the user.

Let me show what HTML will look like for file upload.

<form [formgroup]="form">
  <div class="form-group">
    <label for="file"></label>
    <input type="file" #fileinput="" formcontrolname="fileContact" id="file" required="" (change)="handleFileInput($event.target.files)">
    <button type="button" class="btn btn-info" (click)="clearSelection()">Clear</button>
  </div>
</form>

I have separate posts to set up upload functionality with .NET Web API and .NET Core versions. Both do the same functionality however, the way you read the files is a little different.

Reference Posts:

Conclusion

In this post, I showed how to upload a file from Angular 9 with .NET Core. That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post How to upload a file from Angular 9 with .NET Core Web API appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2020/04/05/how-to-upload-a-file-from-angular-9-with-net-core-web-api/feed/ 2 451
How to upload a file with .NET CORE Web API 3.1 using IFormFile https://blogs.learnsmartcoding.com/2020/04/04/how-to-upload-a-file-with-net-core-web-api-3-1-using-iformfile/ https://blogs.learnsmartcoding.com/2020/04/04/how-to-upload-a-file-with-net-core-web-api-3-1-using-iformfile/#respond Sat, 04 Apr 2020 15:41:08 +0000 https://karthiktechblog.com/?p=434 In this post, I will show how to upload a file with .NET CORE Web API 3.1 using IFormFile. Uploading a file is a process of uploading a file from the user’s system to a hosted web application server. You may choose to store the file in the web server’s local disc or in the […]

The post How to upload a file with .NET CORE Web API 3.1 using IFormFile appeared first on Learn Smart Coding.

]]>
In this post, I will show how to upload a file with .NET CORE Web API 3.1 using IFormFile.

Uploading a file is a process of uploading a file from the user’s system to a hosted web application server. You may choose to store the file in the web server’s local disc or in the database.

With ASP NET CORE, it is easy to upload a file using IFormFile that comes under the namespace "Microsoft.AspNetCore.Http". IFormFile represents a file sent with the HttpRequest.

Upload File using IFormFile in .NET Core

Methods of uploading files have changed since DOT NET CORE was introduced. To upload a single file using .NET CORE Web API, use IFormFile which Represents a file sent with the HttpRequest.

This is how a controller method looks like which accepts a single file as a parameter.

[HttpPost("upload", Name = "upload")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> UploadFile(
         IFormFile file,
         CancellationToken cancellationToken)
        {
            if (CheckIfExcelFile(file))
            {
                await WriteFile(file);
            }
            else
            {
                return BadRequest(new { message = "Invalid file extension" });
            }

            return Ok();
        }

Code Explanation

The controller action method “UploadFile” accepts file using IFormFile as a parameter. We check whether the file sent is in the required format using a custom private method named “CheckIfExcelFile” which checks whether an incoming file is an excel file. You may change this based on your needs.

       
 private bool CheckIfExcelFile(IFormFile file)
        {
            var extension = "." + file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
            return (extension == ".xlsx" || extension == ".xls"); // Change the extension based on your need
        }

Once the validation is a success, we save the file to the disc using “WriteFile(file)” method.

private async Task<bool> WriteFile(IFormFile file)
        {
            bool isSaveSuccess = false;
            string fileName;
            try
            {
                var extension = "." + file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
                fileName = DateTime.Now.Ticks + extension; //Create a new Name for the file due to security reasons.

                var pathBuilt = Path.Combine(Directory.GetCurrentDirectory(), "Upload\\files");

                if (!Directory.Exists(pathBuilt))
                {
                    Directory.CreateDirectory(pathBuilt);
                }

                var path = Path.Combine(Directory.GetCurrentDirectory(), "Upload\\files",
                   fileName);

                using (var stream = new FileStream(path, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                isSaveSuccess = true;
            }
            catch (Exception e)
            {
               //log error
            }

            return isSaveSuccess;
        }

Yes, to upload a file with .NET CORE Web API 3.1 using IFormFile is very easy with DOTNET CORE Web API.

How to upload a file with .NET CORE Web API 3.1 using IFormFile

Here is the short video tutorial.

Upload file from Angular, Video demo

Complete Code

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace KarthikTechBlog.API.Controllers
{
    [HttpPost("upload", Name = "upload")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> UploadFile(
         IFormFile file,
         CancellationToken cancellationToken)
        {
            if (CheckIfExcelFile(file))
            {
                await WriteFile(file);
            }
            else
            {
                return BadRequest(new { message = "Invalid file extension" });
            }

            return Ok();
        }

        /// 
        /// Method to check if file is excel file
        /// 
        /// 
        /// 
        private bool CheckIfExcelFile(IFormFile file)
        {
            var extension = "." + file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
            return (extension == ".xlsx" || extension == ".xls"); // Change the extension based on your need
        }

        private async Task<bool> WriteFile(IFormFile file)
        {
            bool isSaveSuccess = false;
            string fileName;
            try
            {
                var extension = "." + file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
                fileName = DateTime.Now.Ticks + extension; //Create a new Name for the file due to security reasons.

                var pathBuilt = Path.Combine(Directory.GetCurrentDirectory(), "Upload\\files");

                if (!Directory.Exists(pathBuilt))
                {
                    Directory.CreateDirectory(pathBuilt);
                }

                var path = Path.Combine(Directory.GetCurrentDirectory(), "Upload\\files",
                   fileName);

                using (var stream = new FileStream(path, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                isSaveSuccess = true;
            }
            catch (Exception e)
            {
               //log error
            }

            return isSaveSuccess;
        }
    }
}

GitHub Code

You can get the complete code from github https://github.com/karthiktechblog/UploadFileUsingDotNETCore

Reference

Read more about IFormFile Interface
To upload multiple files, use IFormFileCollection Interface

Related Posts

Conclusion

In this post, I showed how to upload a file with .NET CORE Web API 3.1 using IFormFile. That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post How to upload a file with .NET CORE Web API 3.1 using IFormFile appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2020/04/04/how-to-upload-a-file-with-net-core-web-api-3-1-using-iformfile/feed/ 0 434
How to upload a file in ASP.NET Web API https://blogs.learnsmartcoding.com/2020/04/04/how-to-upload-a-file-in-asp-net-web-api/ https://blogs.learnsmartcoding.com/2020/04/04/how-to-upload-a-file-in-asp-net-web-api/#respond Sat, 04 Apr 2020 15:18:07 +0000 https://karthiktechblog.com/?p=430 In this short post, I will show how to upload a file in ASP.NET Web API. In this example, I will be using FormData to upload a file from any UI technology like JavaScript, Angular and much more. Using FormData FormData provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. The form uses “multipart/form-data” as encoding type and FormData does the same. […]

The post How to upload a file in ASP.NET Web API appeared first on Learn Smart Coding.

]]>
In this short post, I will show how to upload a file in ASP.NET Web API. In this example, I will be using FormData to upload a file from any UI technology like JavaScript, Angular and much more.

Using FormData

FormData provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method.

The form uses “multipart/form-data” as encoding type and FormData does the same.

Let’s jump into the coding part to see how to upload a file in ASP.NET Web API.

Upload Example

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.Http;

namespace KarthikTechBlog.API.Controllers
{
    public class UploadController : ApiController
    {
        private readonly string uploadPath ="~/App_Data/uploads";
        private readonly List allowedFileExtensions = new List() { "pdf", "xlx", "doc", "docx", "xlxs" };

        [HttpPost]
        [ActionName("UploadFile")]
        public async Task UploadFile()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            
            var provider = new MultipartMemoryStreamProvider();

            await Request.Content.ReadAsMultipartAsync(provider);

            var file = provider.Contents.FirstOrDefault();

            var fileExtension = file.Headers.ContentDisposition.FileName.Split('.')[1];
            if (!allowedFileExtensions.Any(a => a.Equals(fileExtension)))
            {
                return BadRequest($"File with extension {fileExtension} is not allowed");
            }

            await SaveFileToDisc(file, fileExtension); 
            
            await SaveFileToDatabase(file);

            return Ok();
        }

        private async Task SaveFileToDisc(HttpContent file, string extension)
        {
            var fileName = $"{DateTime.Now.Ticks}.{extension}"; 

            var root = System.Web.HttpContext.Current.Server.MapPath(uploadPath);

            var pathBuilt = Path.Combine(root, string.Concat(DateTime.Now.Month.ToString(), DateTime.Now.Day.ToString(), DateTime.Now.Year.ToString()));

            if (!Directory.Exists(pathBuilt))
            {
                Directory.CreateDirectory(pathBuilt);
            }

            var path = Path.Combine(pathBuilt, fileName);

            using (var stream = new FileStream(path, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
        }

        private async Task SaveFileToDatabase(HttpContent file)
        {
            var byteArray = await file.ReadAsByteArrayAsync();
            var base64String = Convert.ToBase64String(byteArray); // Save this base64 string to database
        }

    }
}

With upload functionality, you can save the incoming file to a disc or save the file to a database after encoding the file to standard Base64 string. You may also perform both operations like saving the file to disc and to the database.

Are you looking for similar upload functionality in ASP NET CORE 3.1? Read this post for more details.

Reference

to read more about MultipartMemoryStreamProvider, visit MultipartStreamProvider Class in MSDN

Related Posts

Conclusion

In this post, I showed how to upload a file in ASP.NET Web API. That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post How to upload a file in ASP.NET Web API appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2020/04/04/how-to-upload-a-file-in-asp-net-web-api/feed/ 0 430