.net 6 mvc+ layui upload实现上传文件
时间: 2025-03-07 15:11:31 浏览: 55
### 实现 .NET 6 MVC 和 Layui 的文件上传
在 ASP.NET Core 6.0 版本中,可以利用 `IFormFile` 接口处理文件上传操作[^2]。对于前端部分,则可以通过集成 Layui 来构建用户界面并发送 AJAX 请求给服务器端。
#### 后端代码示例
创建名为 TestController 的控制器,在其中定义用于接收文件的数据传输对象 DTO 类型以及 POST 方法:
```csharp
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication.Controllers {
public class FileUploadResultDto {
public int Code { get; set; }
public string Msg { get; set; }
public List<string> Data { get; set; }
}
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase {
[HttpPost("[action]")]
public IActionResult UploadImg(IFormFile file) {
try {
if (file.Length > 0) {
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads/", file.FileName);
using(var stream = new FileStream(filePath, FileMode.Create)) {
file.CopyTo(stream);
}
return Json(new FileUploadResultDto() {
Code = 0,
Msg = "Success",
Data = new List<string>() {$"/uploads/{file.FileName}"}
});
} else {
throw new Exception("No file uploaded.");
}
} catch(Exception ex){
return Json(new FileUploadResultDto(){
Code=-1,
Msg=ex.Message,
Data=new List<string>()
});
}
}
}
}
```
此段 C# 代码展示了如何通过 IFormFile 参数获取客户端提交过来的文件,并将其保存至指定目录下;成功后返回 JSON 响应告知前端状态码、消息体及新生成资源链接地址列表[^1]。
#### 前端 HTML + JavaScript 部分
为了简化页面布局工作量,这里采用 Layui 提供的一套简单易用组件库来完成表单设计任务。具体来说就是引入官方 CDN 资源包之后再编写如下所示的静态网页片段即可满足需求:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Layui Image Uploader</title>
<!-- Import CSS -->
<link rel="stylesheet" href="//unpkg.com/layui/dist/css/layui.css"/>
<body>
<form id="upload-form" method="post" enctype="multipart/form-data">
<div style="margin-top:5%;">
<button type="button" class="layui-btn" id="test1">Choose Files</button>
<button type="submit" class="layui-btn">Submit</button>
</div>
<img src="" alt="" id="img1" width="100px;" height="auto;">
<p><span id="ImgUrl"></span></p>
<a href="#" onclick="$(this).hide();" class="deleteImg layui-btn layui-btn-danger" hidden>Delete Picture</a>
<script src="//unpkg.com/layui/dist/layui.js"></script>
<script>
layui.use(['form','element'],function () {
var form = layui.form;
var element = layui.element;
var $ = layui.jquery;
// Initialize uploader component
layui.upload({
url:'/api/test/uploadimg',
elem:'#test1'
,dataType:'json'
,before:function(obj){obj.preview(function(index,file,result){}
})
,done:function(res){
if(res.code===0){
layer.msg('Uploaded successfully!',{icon:1,time:2e3});
$('#img1').attr('src',res.data[0]);
$('#ImgUrl').text(res.data.join());
$('.deleteImg').show();
}else{
layer.alert(res.msg,{icon:2,title:'Error'});
}
},error:function(){
layer.alert('Request failed',{icon:2,title:'Error'});
}});
});
</script>
</body>
</html>
```
上述脚本实现了当点击按钮触发选择对话框选取目标图像文件时自动发起异步请求向后台传送所选项目;一旦接收到回复则依据响应内容更新 DOM 结构显示预览缩略图与绝对路径字符串[^3]。
阅读全文
相关推荐












using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
[LoginActionFitter]
public class UserManagemController : Controller
{
// GET: UserManagem
AoutEntities1 db = new AoutEntities1();
ReturnListJsonData jsonListData = new ReturnListJsonData();
public ActionResult Index()
{
return View();
}
///
/// 列表展示
///
///
///
///
///
/// <returns></returns>
public ActionResult GetList(int page,int limit,string name,string code)
{
var list = db.Users.ToList();
if (!string.IsNullOrEmpty(name))
{
list = list.Where(a => a.UserName.Contains(name)).ToList();
}
if (!string.IsNullOrEmpty(code))
{
list = list.Where(a => a.UserCode.Contains(code)).ToList();
}
var offset = (page - 1) * limit;
var resultList = list.Skip(10).Take(limit);
jsonListData.code = 0;
jsonListData.count = list.Count;
jsonListData.data = resultList;
return Json(jsonListData,JsonRequestBehavior.AllowGet);
}
}
}
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<script src="~/Scripts/layui/layui.js"></script>
<script src="~/Scripts/jquery-3.4.1.js"></script>
<style>
body {
padding: 10px 20px 20px 20px;
width: 90%
}
.but {
margin-top: -5px
}
.editInfo {
display: none;
}
</style>
</head>
<body>
<fieldset class="layui-elem-field">
<legend>
基本信息管理
员工管理
</legend>
<label class="layui-form-label" style="width: 60px;">员工账号</label>
<input type="text" name="code" id="code" autocomplete="off" class="layui-input">
<label class="layui-form-label" style="width: 60px;">员工姓名</label>
<input type="text" name="name" id="name" autocomplete="off" class="layui-input">
<button type="button" class="layui-btn layui-btn-radius but" id="searchButton" onclick="Search()">查询</button>
<button type="button" class="layui-btn layui-bg-blue but" onclick="Add()">添加</button>
<button type="button" class="layui-btn layui-btn-danger layui-btn-radius">批量删除</button>
<button type="button" class="layui-btn layui-btn-danger layui-btn-radius">导出</button>
<button type="button" class="layui-btn but" id="searchButton">导入文件</button>
</fieldset>
<fieldset class="layui-elem-field">
<script type="text/html" id="toolDemo">
编辑
删除
</script>
</fieldset>
<script>
var tableIns;
var form;
var isEdit;
layui.use(['table', 'form',], function () {
var table = layui.table;
form = layui.form; // 修正:移除重复的var声明
// 创建渲染实例
tableIns = table.render({
elem: '#test',
url: '/UserManagem/GetList',
page: true,
cols: [[
{ type: 'checkbox', width: '5%', title: '' },
{ type: 'numbers', width: '5%', title: '序号' },
{ field: 'UserCode', width: '8%', title: '员工账号' },
{ field: 'UserName', width: '8%', title: '员工姓名' },
{
field: 'Sex', width: '8%', title: '性别', templet: function (d) {
return d.Sex ? "男" : "女"; // 修正:使用大写的Sex
}
},
{
field: 'BirthDay', width: '8%', title: '出生日期', templet: function (d) {
return convertJsonDate(d.BirthDay);
}
},
{
field: 'BirthDay', width: '8%', title: '年龄', templet: function (d) {
return calculateAge(d.BirthDay);
}
},
{
field: 'Status', width: '8%', title: '是否离职', templet: function (d) {
return d.Status ? "离职" : "在职";
}
},
{ field: 'Email', width: '8%', title: '邮箱' },
{ field: 'Tel', width: '8%', title: '电话' },
{
field: 'CreateDate', width: '8%', title: '创建时间', templet: function (d) {
return convertJsonDate(d.CreateDate);
}
},
{ field: 'Address', width: '8%', title: '员工住址' },
{ title: '操作', width: '8%', templet: '#toolDemo' }
]],
done: function (res, curr, count) {
// 数据渲染完成后的回调
if (res.code !== 0) { // 假设0是成功状态码
layer.msg('数据加载失败: ' + res.msg, { icon: 5 });
}
},
error: function () {
// 请求错误的回调
layer.msg('网络请求错误,请检查接口', { icon: 5 });
}
});
});
// 处理日期格式函数
function convertJsonDate(jsonDate) {
if (!jsonDate) return '';
try {
// 提取时间戳
const timestamp = parseInt(jsonDate.match(/\d+/)[0]);
// 创建 Date 对象
const date = new Date(timestamp);
// 获取年、月、日
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
// 返回格式化后的日期
return ${year}-${month}-${day};
} catch (e) {
console.error('日期格式化错误:', e);
return jsonDate;
}
}
function calculateAge(jsonBirthDate) {
if (!jsonBirthDate) return '';
try {
// 先转换为日期格式
const birthDate = convertJsonDateToDate(jsonBirthDate);
const today = new Date();
let age = today.getFullYear() - birthDate.getFullYear();
const monthDiff = today.getMonth() - birthDate.getMonth();
if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
} catch (e) {
console.error('年龄计算错误:', e);
return '';
}
}
// 辅助函数:将JSON日期转换为Date对象
function convertJsonDateToDate(jsonDate) {
const timestamp = parseInt(jsonDate.match(/\d+/)[0]);
return new Date(timestamp);
}
</script>
</body>
</html>
这是我的前后段代码 但员工数据展示不出来

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using WebApplication1.Models; namespace WebApplication1.Controllers { [LoginActionFitter] public class UserManagemController : Controller { // GET: UserManagem AoutEntities1 db = new AoutEntities1(); ReturnListJsonData jsonListData = new ReturnListJsonData(); ReturnJsonData jsonData = new ReturnJsonData(); public ActionResult Index() { return View(); } /// /// 列表展示 /// /// /// /// /// /// public ActionResult GetList(int page,int limit,string name,string code) { var list = db.Users.ToList(); if (!string.IsNullOrEmpty(name)) { list = list.Where(a => a.UserName.Contains(name)).ToList(); } if (!string.IsNullOrEmpty(code)) { list = list.Where(a => a.UserCode.Contains(code)).ToList(); } var offset = (page - 1) * limit; var resultList = list.Skip(offset).Take(limit); jsonListData.code = 0; jsonListData.count = list.Count; jsonListData.data = resultList; return Json(jsonListData,JsonRequestBehavior.AllowGet); } #region 删除 /// /// 删除数据 /// /// public ActionResult DelInfo(Guid? id) { if (id == Guid.Empty) { jsonData.code = 1; jsonData.msg = “删除失败,未找到当行数据”; } else { //真实删除 var entity1 = db.Users.Find(id); db.Users.Remove(entity1); var result = db.SaveChanges(); if (result > 0) { jsonData.code = 0; jsonData.msg = “删除成功”; } else { jsonData.code = 1; jsonData.msg = “删除失败,请联系管理员”; } } return Json(jsonData, JsonRequestBehavior.AllowGet); } #endregion } } @{ Layout = null; } <!DOCTYPE html> <html> <head> <script src="~/Scripts/layui/layui.js"></script> <script src="~/Scripts/jquery-3.4.1.js"></script> <style> body { padding: 10px 20px 20px 20px; width: 97% } .but { margin-top: -5px } .editInfo { display: none; } </style> </head> <body> <fieldset class="layui-elem-field"> <legend> 基本信息管理 员工管理 </legend> <label class="layui-form-label" style="width: 60px;">员工账号</label> <input type="text" name="code" id="code" autocomplete="off" class="layui-input"> <label class="layui-form-label" style="width: 60px;">员工姓名</label> <input type="text" name="name" id="name" autocomplete="off" class="layui-input"> <button type="button" class="layui-btn layui-btn-radius but" id="searchButton" onclick="Search()">查询</button> <button type="button" class="layui-btn layui-bg-blue but" onclick="Add()">添加</button> <button type="button" class="layui-btn layui-btn-danger layui-btn-radius">批量删除</button> <button type="button" class="layui-btn layui-btn-danger layui-btn-radius">导出</button> <button type="button" class="layui-btn but" id="searchButton">导入文件</button> </fieldset> <fieldset class="layui-elem-field"> <script type="text/html" id="toolDemo"> 编辑 删除 </script> </fieldset> <script> var tableIns; var form; var isEdit; layui.use(['table', 'form',], function () { var table = layui.table; form = layui.form; // 修正:移除重复的var声明 // 创建渲染实例 tableIns = table.render({ elem: '#test', url: '/UserManagem/GetList', page: true, cols: [[ { type: 'checkbox', width: '5%', title: '' }, { type: 'numbers', width: '5%', title: '序号' }, { field: 'UserCode', width: '8%', title: '员工账号' }, { field: 'UserName', width: '8%', title: '员工姓名' }, { field: 'Sex', width: '8%', title: '性别', templet: function (d) { return d.Sex ? "男" : "女"; // 修正:使用大写的Sex } }, { field: 'BirthDay', width: '8%', title: '出生日期', templet: function (d) { return convertJsonDate(d.BirthDay); } }, { field: 'BirthDay', width: '8%', title: '年龄', templet: function (d) { return calculateAge(d.BirthDay); } }, { field: 'Status', width: '8%', title: '是否离职', templet: function (d) { return d.Status ? "离职" : "在职"; } }, { field: 'Email', width: '8%', title: '邮箱' }, { field: 'Tel', width: '8%', title: '电话' }, { field: 'CreateDate', width: '8%', title: '创建时间', templet: function (d) { return convertJsonDate(d.CreateDate); } }, { field: 'Address', width: '8%', title: '员工住址' }, { title: '操作', width: '10.5%', templet: '#toolDemo' } ]], done: function (res, curr, count) { // 数据渲染完成后的回调 if (res.code !== 0) { // 假设0是成功状态码 layer.msg('数据加载失败: ' + res.msg, { icon: 5 }); } }, error: function () { // 请求错误的回调 layer.msg('网络请求错误,请检查接口', { icon: 5 }); } }); //编辑,删除 table.on('tool(test)', function (obj) { // 双击 toolDouble var data = obj.data; // 获得当前行数据 var field = obj.field; // 得到字段 var value = obj.value; // 得到修改后的值 var data = obj.data; // 得到所在行所有键值 // console.log(obj) if (obj.event === 'edit') { //编辑 //修改编辑职位 layer.open({ type: 1, // page 层类型 area: ['500px', '300px'], title: '编辑职位', shade: 0.6, // 遮罩透明度 shadeClose: false, // 点击遮罩区域,关闭弹层 maxmin: false, // 允许全屏最小化 anim: 0, // 0-6 的动画形式,-1 不开启 content: $(".editInfo").html() }); //赋值 form.val('demo-val-filter', { "jobname": data.JobName, "jobcode": data.JobCode, "ID": data.ID }); } else { layer.confirm('真的删除员工 [' + data.UserCode + '] 么', function (index) { obj.del(); // 删除对应行(tr)的DOM结构 layer.close(index); // 向服务端发送删除指令 $.ajax({ url: '/UserManagem/DelInfo', type: 'post', data: { id: data.ID }, success: function (res) { if (res.code == 0) { layer.msg(res.msg, { icon: 6, time: 1500 }, function () { Search(); }) } else { layer.msg(res.msg, { icon: 5, time: 1500 }) } } }) }); } }); }); // 处理日期格式函数 function convertJsonDate(jsonDate) { if (!jsonDate) return ''; try { // 提取时间戳 const timestamp = parseInt(jsonDate.match(/\d+/)[0]); // 创建 Date 对象 const date = new Date(timestamp); // 获取年、月、日 const year = date.getFullYear(); const month = (date.getMonth() + 1).toString().padStart(2, '0'); const day = date.getDate().toString().padStart(2, '0'); // 返回格式化后的日期 return ${year}-${month}-${day}; } catch (e) { console.error('日期格式化错误:', e); return jsonDate; } } //表单提交事件,新增和编辑 form.on('submit(demo1)', function (data) { var field = data.field; // 获取表单字段值 $.ajax({ url: '/UserManagem/Add', type: 'post', data: field, success: function (res) { if (res.code == 0) { layer.msg(res.msg, { icon: 6, time: 3000 }, function () { layer.closeAll(); // 关闭所有类型的层 Search(); }); } else { layer.msg(res.msg, { icon: 5, time: 2000 }); } } }) }) //重载,模糊查询 function Search() { var nameVal = $('input[name="name"]').val().trim(); var codeVal = $('input[name="code"]').val().trim(); // 完整重载 - 所有属性属性(options)均可参与到重载中 tableIns.reload({ where: { // 传递数据异步请求时携带的字段 name: nameVal, code: codeVal }, height: 500 // 重设高度 }); } // 处理日期格式函数 function convertJsonDate(jsonDate) { // 提取时间戳 const timestamp = parseInt(jsonDate.match(/\d+/)[0]); // 创建 Date 对象 const date = new Date(timestamp); // 获取年、月、日 const year = date.getUTCFullYear(); const month = (date.getUTCMonth() + 1).toString().padStart(2, '0'); const day = date.getUTCDate().toString().padStart(2, '0'); // 返回格式化后的日期 return ${year}-${month}-${day}; } //新增职位 function Add() { // 在此处输入 layer 的任意代码 layer.open({ type: 1, // page 层类型 area: ['500px', '300px'], title: '新建职位', shade: 0.6, // 遮罩透明度 shadeClose: false, // 点击遮罩区域,关闭弹层 maxmin: false, // 允许全屏最小化 anim: 0, // 0-6 的动画形式,-1 不开启 content: $(".editInfo").html() }); } function calculateAge(jsonBirthDate) { if (!jsonBirthDate) return ''; try { // 先转换为日期格式 const birthDate = convertJsonDateToDate(jsonBirthDate); const today = new Date(); let age = today.getFullYear() - birthDate.getFullYear(); const monthDiff = today.getMonth() - birthDate.getMonth(); if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) { age--; } return age; } catch (e) { console.error('年龄计算错误:', e); return ''; } } // 辅助函数:将JSON日期转换为Date对象 function convertJsonDateToDate(jsonDate) { const timestamp = parseInt(jsonDate.match(/\d+/)[0]); return new Date(timestamp); } </script> </body> </html> 编辑以及添加功能没有完成请你续写仿照我的代码风格




