无法使用.net Core 2.1上传文件

时间:2018-08-08 17:25:37

标签: .net-core asp.net-core-2.0

我正在努力获取一个基本的文件上传示例,以使用.NET Core 2.1进行工作。我的技术基于此.NET Core file upload article,使用了该文章顶部的简单“小文件”示例。

当我调用文件上传时,没有任何文件发布到Upload方法...

enter image description here

有人可以看到这里缺少的东西吗?看起来很简单,但是却行不通。

这是重现我当前状态所需的最少代码。

我做了“文件/新项目/ASP.NET Core Web应用程序”,并使用了该项目模板...

enter image description here

我删除了样板UI,并使用简化的项目结构创建了自己的版本...

enter image description here

Index.cshtml

<!DOCTYPE html>
<html>
<body>
    <input type="file" />

    <script src="~/lib/jquery/dist/jquery.js"></script>
    <script type="text/javascript">
        $(function () {
            $('input[type="file"]').change(function (e) {
                let formData = new FormData();

                for (let x = 0; x < this.files.length; x++) {
                    let file = this.files[x];
                    formData.append(file.name, file);
                }

                $.ajax({
                    type: 'POST',
                    url: './Home/Upload',
                    contentType: false,
                    processData: false,
                    data: formData,
                    success: function (message) {
                    }
                });
            });
        });
    </script>
</body>
</html>

HomeController.cs

using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace FileUploadIssue.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Upload (List<IFormFile> files)
        {
            return Ok();
        }
    }
}

Program.cs(与项目模板相同)

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace FileUploadIssue
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

Startup.cs(与项目模板相同)

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace FileUploadIssue
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

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

appsettings.json(与项目模板相同)

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

2 个答案:

答案 0 :(得分:3)

感谢您关注我的教程:)

问题出在您的jQuery,特别是这段代码:

for (let x = 0; x < this.files.length; x++) {
    let file = this.files[x];
    formData.append(file.name, file);
}

append方法的第一个参数实际上是“表单输入”名称的名称,而不是文件名(当您将文件附加到文件名时,它将自动附加到请求中)。

如果您将代码更改为:

for (let x = 0; x < this.files.length; x++) {
    let file = this.files[x];
    formData.append('files', file);
}

你们都很高兴。

答案 1 :(得分:0)

如果要启用上传多个文件,请将<input type="file" />更改为以下内容:

<input type="file"  multiple />