Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload Large Files using Angular 8 and .Net Core Web API

I'm trying to upload large files to server directory using .Net core Web Api as backend and Angular 8 as frontend.

UploadComponent.ts

import { Component } from '@angular/core';
import { HttpClient, HttpRequest, HttpEventType, HttpResponse } from '@angular/common/http'


@Component({
  selector: 'app-uploader',
  templateUrl: './uploader.component.html',
})
export class UploadComponent {
  public progress: number;
  public message: string;
  constructor(private http: HttpClient) { }

  upload(files) {
    if (files.length === 0)
      return;

    const formData = new FormData();

    for (let file of files)
      formData.append(file.name, file);

    const uploadReq = new HttpRequest('POST', `api/upload`, formData, {
      reportProgress: true,
    });

    this.http.request(uploadReq).subscribe(event => {
      if (event.type === HttpEventType.UploadProgress)
        this.progress = Math.round(100 * event.loaded / event.total);
      else if (event.type === HttpEventType.Response)
        this.message = event.body.toString();
    });
  }
}

Upload Component HTML

<input #file type="file" multiple (change)="upload(file.files)" />
<br />
<span style="font-weight:bold;color:green;" *ngIf="progress > 0 && progress < 100">
  {{progress}}%
</span>

<span style="font-weight:bold;color:green;" *ngIf="message">
  {{message}}
</span>

<p><progress showValue="true" type="success" value={{progress}} max="100"></progress></p>

UploadController

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

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace WebApplication2.Controllers
{
        [Produces("application/json")]
        [Route("api/[controller]")]
        public class UploadController : Controller
        {
            private IHostingEnvironment _hostingEnvironment;

            public UploadController(IHostingEnvironment hostingEnvironment)
            {
                _hostingEnvironment = hostingEnvironment;

            }

            [HttpPost, DisableRequestSizeLimit]
            public ActionResult UploadFile()
            {

                try
                {
                    var file = Request.Form.Files[0];
                    string folderName = "Upload";
                    string webRootPath = _hostingEnvironment.WebRootPath;
                    string newPath = Path.Combine(webRootPath, 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 Json("Upload Successful.");
                }
                catch (System.Exception ex)
                {
                    return Json("Upload Failed: " + ex.Message);
                }
            }
        }

}

This works fine for small files.But when it comes to large files,the control never passes to the Web Controller.There is this error in the console enter image description here

like image 492
techno Avatar asked Oct 17 '25 15:10

techno


1 Answers

I think the problem is requestLimits->maxAllowedContentLength property in .net core configuration.here is the link to resolve it in iis and kestrel

like image 114
Ehsan Kiani Avatar answered Oct 19 '25 05:10

Ehsan Kiani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!