Base solution for your next web application
Ends in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

Upload File Error with size larger 30MB ? #9802


User avatar
0
sempus created

Hi, I'm using ASPNETZERO Ver 8.7.0 (Angular + .Net Core 3.1) I have problem with Upload File larger 30MB ( It's Ok with file smaller 30MB)

In Logs.txt not Error

INFO  2020-11-03 10:55:49,256 [81   ] Microsoft.AspNetCore.Hosting.Diagnostics - Request starting HTTP/2.0 OPTIONS https://localhost:44310/KeHoachKsclNoiDungClFile/UploadFiles  
INFO  2020-11-03 10:55:49,257 [81   ] pNetCore.Cors.Infrastructure.CorsService - CORS policy execution successful.
INFO  2020-11-03 10:55:49,257 [81   ] Microsoft.AspNetCore.Hosting.Diagnostics - Request finished in 0.5664ms 204 

This is my example: In Angular Component.html:

<p-fileUpload multiple="multiple" id="KeHoachKsclNoiDungClFileInput" customUpload="true"
        #KeHoachKsclNoiDungClFileInput name="KeHoachKsclNoiDungClFileInput[]" maxFileSize="104857600"
        [showUploadButton]="false" [showCancelButton]="false"  [auto]="true"
        (uploadHandler)="uploadKeHoachKsclNoiDungClFile($event)"
        (onError)="onUploadKeHoachKsclNoiDungClFileError()">
    </p-fileUpload>

In Angular component.ts:

uploadKeHoachKsclNoiDungClFileUrl: string;
...
@ViewChild('KeHoachKsclNoiDungClFileInput', { static: false }) keHoachKsclNoiDungClFileInput: FileUpload;
....
constructor(
        injector: Injector,
        private _keHoachKsclNoiDungClFileServiceProxy: KeHoachKsclNoiDungClFileServiceProxy,
        private _httpClient: HttpClient
    ) {
        super(injector);
        this.uploadKeHoachKsclNoiDungClFileUrl = AppConsts.remoteServiceBaseUrl + '/KeHoachKsclNoiDungClFile/UploadFiles';
}
...
uploadKeHoachKsclNoiDungClFile(event): void {
        let index = 0;
        const formData: FormData = new FormData();
        for (const file of event.files) {
            index++;
            formData.append('file', file, `${index.toString()}-${file.name}`);
        }

        this._httpClient
            .post<any>(this.uploadKeHoachKsclNoiDungClFileUrl, formData)
            .pipe(
                takeWhile(() => this.componentActive),
                mergeMap(response => {
                    if (response.success) {
                        return this._keHoachKsclNoiDungClFileServiceProxy.getKeHoachKsclNoiDungClFileByKeHoachKsclNoiDungClId(this.keHoachKsclNoiDungClModal.id);
                    } else if (response.error != null) {
                        this.notify.error(this.l('ProcessFileError', this.l('Checklist')), this.l('Notification'));
                        return of([]);
                    }
                }),
                catchError(() => {
                    this.notify.error(this.l('NoiDungKsclChecklistFileError'), this.l('Notification'));
                    return of(null);
                }),
                tap(dataChecklistFiles => {
                    this.keHoachKsclNoiDungClFiles = dataChecklistFiles;
                }),
                finalize(() => this.keHoachKsclNoiDungClFileInput.clear())
            )
            .subscribe();
    }
    
    onUploadKeHoachKsclNoiDungClFileError(): void {
        this.messageService.add({
            severity: 'error',
            summary: this.l('Notification'),
            detail: this.l('NoiDungKsclChecklistFileError'),
            key: 'updateKeHoachKsclNoiDungClModalToast'
        });
    }

In .Net Core Controller:

[HttpPost]
[DisableRequestSizeLimit]
public async Task<List<KeHoachKsclNoiDungClFileDto>> UploadFiles()
{
    try
    {
        var files = Request.Form.Files;
        if (files == null)
            throw new UserFriendlyException(L("File_Empty_Error"));

        var filesOutput = new List<KeHoachKsclNoiDungClFileDto>();
        foreach (var file in files)
        {
            if (file.Length > (1048576 * _fileSizeLimit)) 
                throw new UserFriendlyException(L("File_SizeLimit_Error"));

            var fileObject = ..........(some code get object);
            var fileObjectResult = await _keHoachKsclNoiDungClFileAppService.CreateOrEdit(fileObject);
            filesOutput.Add(fileObjectResult);
        }

        return filesOutput;
    }
    catch (UserFriendlyException ex)
    {
        throw new UserFriendlyException(ex.Message);
    }
}

3 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi @sempus

    This is probably blocked by your web server. If you are using IIS, it has a default limit on file upload. You can change it by following the steps here or you can search alternative approaches on the web.

  • User Avatar
    0
    sempus created

    Hi, I'm running IIS Express VS 2019. I changed my backEnd like that: (But still Error !!!) In ...Web.Host > Program.cs

    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
            {
                return new WebHostBuilder()
                    .UseKestrel(opt =>
                    {
                        opt.AddServerHeader = false;
                        //opt.Limits.MaxRequestLineSize = 16 * 1024;
                        opt.Limits.MaxRequestLineSize = int.MaxValue;
                        opt.Limits.MaxRequestBodySize = long.MaxValue;
                    })
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .UseIIS()
                    .UseIISIntegration()
                    .UseStartup<Startup>();
            }
    

    In ...Web.Host > StartUp.cs > ConfigureServices

    public IServiceProvider ConfigureServices(IServiceCollection services)
            {
                // IIS request body size
                services.Configure<IISServerOptions>(options =>
                {
                    options.MaxRequestBodySize = long.MaxValue;
                });
    
                // Kestrel request body size
                services.Configure<KestrelServerOptions>(options =>
                {
                    options.Limits.MaxRequestBodySize = long.MaxValue; // if don't set default value is: 30 MB
                });
    
                //Multipart body length limit
               services.Configure<FormOptions>(options =>
               {
                   options.ValueLengthLimit = int.MaxValue;
                   options.MultipartBodyLengthLimit = long.MaxValue; // <-- if don't set default value is: 128 MB
                   options.MultipartBoundaryLengthLimit = int.MaxValue;
                   options.MultipartHeadersCountLimit = int.MaxValue;
                   options.MultipartHeadersLengthLimit = int.MaxValue;
               });
    
                //MVC
                services.AddControllersWithViews(options =>
                {
                    options.Filters.Add(new AbpAutoValidateAntiforgeryTokenAttribute());
                }).AddNewtonsoftJson();
                ...
        }
    

    I have seen some posts ng2-file-upload hangs on pending then fails with cors error ( Large Files) Or how to upload big file I tried deploy to use IIS => But not Ok (like IISEXpress)

     <?xml version="1.0" encoding="utf-8"?>
    <configuration>
    	<location path="." inheritInChildApplications="false">
    		<system.web>
    			<!-- ~ 2GB -->
    			<httpRuntime maxRequestLength="2147483647" />
    		</system.web>
    		<system.webServer>
    			<security>
    			  <requestFiltering>
    				<!-- ~ 4GB -->
    				<requestLimits maxAllowedContentLength="4294967295" />
    			  </requestFiltering>
    			</security>
    			<handlers>
    			<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
    			</handlers>
    			<aspNetCore processPath="dotnet" arguments=".\Sp.Portal.Web.Host.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    		</system.webServer>
    	</location>
    </configuration>
    <!--ProjectGuid: 9fc37c62-2105-4d32-9724-7323b959504b-->
    
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi @sempus

    1. Have you tried adding [DisableRequestSizeLimit] to related app service method or controller action ?
    2. If you are using Angular version, did you try html file upload instead of ng2 file upload component ?