0

我面临 2 天的媒体文件上传问题。我已经尝试了社区论坛上提供的所有可能的解决方案。但仍然面临问题。我正在分享到目前为止我尝试过的代码。

Asp.net 核心控制器

        //[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);
            }
          

或 API 控制器

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

jQuery代码

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代码

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

启动.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?}");
            });

        }
    }

如果你能帮助我,我将非常感谢你。

4

2 回答 2

0

改变这个:

[HttpPost("UploadVideo"), RequestFormLimits(MultipartBodyLengthLimit = Int16.MaxValue, ValueLengthLimit = Int32.MaxValue),DisableRequestSizeLimit]

至:

[HttpPost("UploadVideo"), RequestFormLimits(MultipartBodyLengthLimit = long.MaxValue, ValueLengthLimit = Int32.MaxValue),DisableRequestSizeLimit]
于 2020-06-29T09:38:47.320 回答
0

我刚刚在同事的帮助下解决了这个问题。感谢大家。因为你参与。

我刚刚添加了 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>

我还添加了

        [HttpPost]
        [DisableRequestSizeLimit]
        public IActionResult Upload([FromForm] IFormFile media)
        {
            if (media != null)
            {
                new HomeController().Run(media).Wait();
               
                return Ok(media.FileName);
            }
            return NotFound();
        }
于 2020-06-29T13:50:26.033 回答