Search code examples
c#asp.netasp.net-coreasp.net-core-webapiiformfile

How to increase or set the upload media file size unlimited in ASP.NET Core 2.2 project


I am facing a media file upload issue for 2 days. I have already tried all the possible solutions given at the community forum. but still facing issues. I'm sharing the code I have tried so far.

Asp.net core Controller

        //[HttpPost]
        //[RequestFormLimits(MultipartBodyLengthLimit = 100000000)]
        //[RequestSizeLimit(100000000)]
        [HttpPost("UploadVideo"),DisableRequestSizeLimit,RequestFormLimits(MultipartBodyLengthLimit =Int16.MaxValue,ValueLengthLimit =Int32.MaxValue)]
        public IActionResult Upload([FromForm] IFormFile media)
        {
            if (media != null)
            {
                //new HomeController().Run(media).Wait();
               
                return Ok(media.FileName);
            }
          

Or Api Controller

[HttpPost("UploadVideo"), DisableRequestSizeLimit, RequestFormLimits(MultipartBodyLengthLimit = Int16.MaxValue, ValueLengthLimit = Int32.MaxValue)]
public ActionResult Post([FromForm] IFormFile media)
{           
    return new JsonResult(media.FileName);
}

Jquery Code

let ajax = async (_formData) => {

    $.ajax({
        url: '/Home/UploadVideo',
        type: "POST",
        //timeout: 0,
        processData: false, // Not to process data  
        //mimeType: "multipart/form-data",
        contentType: false, // Not to set any content header  
        data: _formData,
        success: function (result) {
            console.log(result);
        },
        error: function(err) {
            let { statusText, status } = err;
            console.log({ statusText, status});
        }
    }); 

    //let headers = new Headers();
    //headers.append("Content-Type", "multipart/form-data");

    //try {
    //    let response = await fetch(
    //        //`/api/FileApi/UploadVideo`,
    //        '/Home/UploadVideo',
    //        { method: "POST", body: _formData },
    //        headers
    //    );
    //    return response.json();
    //} catch (e) {
    //    console.log(e)
    //}

};

$('body').on('click', '#upload', (e) => {
    e.preventDefault();
    let formData = new FormData();

    let getFile = document.getElementById("media-file");
    //$('#media-file').get(0);
   
    if (getFile.files != null) {
        let media = getFile.files[0];
        formData.append('media', media);
        console.log(media);
        ajax(formData);
    }
});

Html Code

<div>
    <form>
        <input type="file" id="media-file" name="media" />
        <button class="btn btn-primary" id="upload">Upload</button>
    </form>
</div>

Startup.cs

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.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            //services.AddHttpClient();
            
        }

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

            //app.UseFileServer();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            //app.UseCors(builder =>
            //builder.AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod());

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

        }
    }

I shall be very thankful to you If you can help me.


Solution

  • I just solved the problem with the help of my colleague. Thanks to all of you. because you participate.

    I just added web.config

        <?xml version="1.0" encoding="utf-8"?>
    <configuration>
        <system.web>
         <httpRuntime maxRequestLength="1048576" />
       </system.web>
       <system.webServer>
         <security>
           <requestFiltering>          
             <requestLimits maxAllowedContentLength="1073741824" />
           </requestFiltering>
         </security>
       </system.webServer>
      </configuration>
    

    I also added

            [HttpPost]
            [DisableRequestSizeLimit]
            public IActionResult Upload([FromForm] IFormFile media)
            {
                if (media != null)
                {
                    new HomeController().Run(media).Wait();
                   
                    return Ok(media.FileName);
                }
                return NotFound();
            }