您好,登录后才能下订单哦!
在现代Web应用程序中,文件上传是一个常见的需求。无论是上传图片、文档还是其他类型的文件,用户通常希望能够一次性上传多个文件。Layui是一个轻量级的前端框架,提供了丰富的UI组件,其中包括文件上传组件。本文将详细介绍如何在.Net Core项目中使用Layui实现多文件上传功能。
在开始之前,确保你已经安装了以下工具和框架:
首先,打开Visual Studio并创建一个新的.Net Core Web应用程序项目。
在项目中引入Layui框架,可以通过以下步骤完成:
wwwroot文件夹下创建一个lib文件夹。layui文件夹复制到wwwroot/lib目录下。Views/Shared/_Layout.cshtml文件中引入Layui的CSS和JS文件:<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - YourAppName</title>
    <link rel="stylesheet" href="~/lib/layui/css/layui.css" />
</head>
<body>
    <div class="container">
        @RenderBody()
    </div>
    <script src="~/lib/layui/layui.js"></script>
    @RenderSection("Scripts", required: false)
</body>
</html>
在Views/Home文件夹下创建一个新的视图文件Upload.cshtml,用于实现文件上传功能。
@{
    ViewData["Title"] = "文件上传";
}
<div class="layui-upload">
    <button type="button" class="layui-btn" id="uploadBtn">上传文件</button>
    <div class="layui-upload-list">
        <table class="layui-table">
            <thead>
                <tr>
                    <th>文件名</th>
                    <th>大小</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="fileList"></tbody>
        </table>
    </div>
</div>
@section Scripts {
    <script>
        layui.use('upload', function () {
            var upload = layui.upload;
            // 多文件上传
            upload.render({
                elem: '#uploadBtn',
                url: '/Home/UploadFiles',
                multiple: true,
                done: function (res) {
                    if (res.code === 0) {
                        layer.msg('上传成功');
                        var html = '';
                        res.data.forEach(function (file) {
                            html += '<tr><td>' + file.name + '</td><td>' + file.size + '</td><td>上传成功</td><td><a href="' + file.url + '" target="_blank">下载</a></td></tr>';
                        });
                        $('#fileList').html(html);
                    } else {
                        layer.msg('上传失败');
                    }
                }
            });
        });
    </script>
}
在Controllers/HomeController.cs文件中,添加一个用于处理文件上传的Action。
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace YourAppName.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Upload()
        {
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> UploadFiles(List<IFormFile> files)
        {
            var uploads = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads");
            if (!Directory.Exists(uploads))
            {
                Directory.CreateDirectory(uploads);
            }
            var result = new List<object>();
            foreach (var file in files)
            {
                if (file.Length > 0)
                {
                    var filePath = Path.Combine(uploads, file.FileName);
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }
                    result.Add(new
                    {
                        name = file.FileName,
                        size = file.Length,
                        url = $"/uploads/{file.FileName}"
                    });
                }
            }
            return Json(new { code = 0, data = result });
        }
    }
}
在Startup.cs文件中,确保已经配置了MVC路由。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}
完成以上步骤后,运行项目并访问/Home/Upload页面,你将看到一个文件上传按钮。点击按钮选择多个文件,文件将被上传到服务器的wwwroot/uploads目录下,并在页面上显示上传结果。
为了防止用户上传过大的文件,可以在Startup.cs中配置文件大小限制。
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<FormOptions>(options =>
    {
        options.MultipartBodyLengthLimit = 104857600; // 100MB
    });
    services.AddControllersWithViews();
}
在Layui的上传组件中,可以通过accept参数限制上传文件的类型。
upload.render({
    elem: '#uploadBtn',
    url: '/Home/UploadFiles',
    multiple: true,
    accept: 'file', // 允许上传所有文件
    // accept: 'image', // 仅允许上传图片
    // accept: 'video', // 仅允许上传视频
    // accept: 'audio', // 仅允许上传音频
    done: function (res) {
        // 上传完成后的回调
    }
});
Layui的上传组件支持显示文件上传进度。可以通过progress参数实现。
upload.render({
    elem: '#uploadBtn',
    url: '/Home/UploadFiles',
    multiple: true,
    progress: function (n) {
        var percent = n + '%';
        layer.msg('上传进度:' + percent);
    },
    done: function (res) {
        // 上传完成后的回调
    }
});
通过本文的介绍,你已经学会了如何在.Net Core项目中使用Layui实现多文件上传功能。从环境准备到前端页面开发,再到后端文件处理,本文详细讲解了每一个步骤。希望本文对你有所帮助,祝你在开发过程中顺利实现文件上传功能。
注意:本文中的代码示例仅供参考,实际项目中可能需要根据具体需求进行调整和优化。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。