后端:Layui实现文件上传功能

今天给大家分享采用AspNet MVC+前端框架LayUi实现文件上传功能,感兴趣的朋友可以学习一下。

文件上传实体(UploadFile.cs)

  public class UploadFile
    {
        public int code { get; set; }   //请求code
        public string msg { get; set; } // 请求消息
        public string src { get; set; } //文件路径
        public string filename { get; set; } //原始文件名
    }

前端代码(Upload.cshtml):

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>文件上传示例</title>
    <link href="~/Content/lib/layui/css/layui.css" 
    rel="stylesheet" />
    <link href="~/Content/css/common.css" rel="stylesheet" />
    <script src="~/Content/lib/layui/layui.js"></script>
</head>
<body>
    <div>
        <div class="layui-input-inline layui-btn-container" 
        style="width: auto;">
            <button type="button" 
            class="layui-btn layui-btn-primary" id="btnUpload">
                <i class="layui-icon">&#xe67c;</i>上传附件
            </button>
            <div id="layer-photos-demo" class="fr">
                <img id="imgPhoto" style="height:100px;width:100px;"
                  src="" alt="">
            </div>
        </div>
        <div>
            <table class="layui-table">
                <colgroup>
                    <col width="150">
                    <col width="200">
                </colgroup>
                <thead>
                    <tr>
                        <th>文件名称</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="uploadList"></tbody>
            </table>
        </div>
    </div>
    <script type="text/javascript">
        layui.use(["upload"], function () {


            var upload = layui.upload;
            var $ = layui.$;
            upload.render({
                elem: '#btnUpload',
                url: '/Upload/UploadFile',
                size: '2048',//文件大小2M
                exts: 'png|gif|jpg|jpeg|zip|rar',//文件扩展名
                done: function (res) {
                    if (res.code == 0) {
                        $("#imgPhoto").attr("src", res.src);
                        $("#uploadList").append("<tr><td>" + 
                        res.filename + "</td><td><a target='_blank' 
                        href='" + res.src + "'>查看</a></td><tr>");
                    }
                }
            });


        });
</script>
</body>
</html>

控制器代码(UploadController.cs)

 // 上传视图
 public ActionResult Upload()
{
            return View();
 }
 // 上传逻辑
public JsonResult UploadFile()
        {
            UploadFile uploadFile = new UploadFile();
            try
            {
                var file = Request.Files[0];    //获取选中文件
                var filecombin = file.FileName.Split('.');
                if (file == null || string.IsNullOrEmpty(
                file.FileName) || file.ContentLength == 0 ||
                filecombin.Length < 2)
                {
                    uploadFile.code = -1;
                    uploadFile.src = "";
                    uploadFile.msg = "上传失败!请检查文件";
                    return Json(uploadFile, 
                    JsonRequestBehavior.AllowGet);
                }
                //定义本地路径位置
                string localPath = Server.MapPath("~/Upload");
                string filePathName = string.Empty; //最终文件名
                string dateStr = DateTime.Now.
                ToString("yyyyMMddHHmmss");
                filePathName = dateStr + "." + filecombin[1];
                //Upload不存在则创建文件夹
                if (!System.IO.Directory.Exists(localPath))
                {
                    System.IO.Directory.CreateDirectory(localPath);
                }
                //保存图片
                file.SaveAs(Path.Combine(localPath, filePathName));
                uploadFile.code = 0;


           uploadFile.filename = filecombin[1];
                uploadFile.src = Path.Combine("/Upload/",
                filePathName);
                uploadFile.msg = "上传成功";
                return Json(uploadFile, 
                JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                uploadFile.code = -1;
                uploadFile.src = "";
                uploadFile.msg = "上传失败!";
                return Json(uploadFile, 
                JsonRequestBehavior.AllowGet);
            }
        }

IT技术分享社区

文章推荐程序员效率:画流程图常用的工具程序员效率:整理常用的在线笔记软件远程办公:常用的远程协助软件,你都知道吗?51单片机程序下载、ISP及串口基础知识硬件:断路器、接触器、继电器基础知识

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT技术分享社区

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值