Home >Web Front-end >Layui Tutorial >Detailed explanation of .net mvc+layui for uploading pictures and texts

Detailed explanation of .net mvc+layui for uploading pictures and texts

尚
forward
2019-11-28 13:42:353540browse

Detailed explanation of .net mvc+layui for uploading pictures and texts

图片上传和展示是互联网应用中比较常见的一个功能,本文图片上传功能前端用到的图片上传控件是layui ,数据库是用的 sql server ,code first开发模式。

一、创建表

因为图片上传之后需要保存路径等信息,所以,得先建一个Image表,表的设计为如下:

Detailed explanation of .net mvc+layui for uploading pictures and texts

下面看实体类和上下文的代码:

1.新建实体类Image.cs

如图:

Detailed explanation of .net mvc+layui for uploading pictures and texts

代码如下:

Image.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Modules
{
    [Table("Info_Image")]
    public class Image
    {
        public Image() {
            IsDelete = false;
        }
        /// <summary>
        /// 主键id
        /// </summary>
        public Guid Id { get; set; }

        /// <summary>
        /// 图片名
        /// </summary>
        [Required]
        [MaxLength(50)]
        public string Name { get; set; }

        /// <summary>
        /// 图片保存链接
        /// </summary>
        [Required]
        [MaxLength(50)]
        public string Url { get; set; }

        /// <summary>
        /// 上传时间
        /// </summary>
        public DateTime UploadTime { get; set; }

        /// <summary>
        /// 备注
        /// </summary>
        [MaxLength(200)]
        public string Remark { get; set; }

        /// <summary>
        /// 是否删除
        /// </summary>
        public bool IsDelete { get; set; }
    }
}

 2.将实体类添加到上下文:

如图:

Detailed explanation of .net mvc+layui for uploading pictures and texts

代码:

MyDbContext.cs

  public DbSet<Image> Images { get; set; }

如果你和我一样是code first开发模式的话,那让程序跑一遍,这个数据表就应该在你的数据库里生成了,哈哈,这只是一个建表的过程,只要表能建好,什么模式都好,哈哈。

二、前端代码

1.新建控制器ImageUploadController.cs,然后创建一个视图Index.cshtml:

这里会用到layui的图片上传,关于这部分的代码使用,可以自行去layui官网查看:https://www.layui.com/demo/upload.html;

以下是页面图片,以及代码:

这是还没编写后台上传图片代码时的页面图片:

Detailed explanation of .net mvc+layui for uploading pictures and texts

以下是前端代码:

@{
    Layout = "../Shared/_TopLayout.cshtml";
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div id="picUpload">
        <div class="layui-form-item">
            <label class="layui-form-label required">图片标题</label>
            <div class="layui-input-block" style="width: 554px; position: relative;">
                <input type="text" name="ImageTitle" lay-verify="required" placeholder="图片标题" autocomplete="off" class="layui-input" id="ITitle">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block" style="width: 554px; position: relative;">
                <textarea placeholder="请输入内容" class="layui-textarea" name="Remark"></textarea>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-upload">
                <label class="layui-form-label">上传图片</label>
                <button type="button" class="layui-btn" id="test1">上传图片</button>
                <div class="layui-upload-list">
                    <label class="layui-form-label">图片展示</label>
                    <img  class="layui-upload-img" id="demo1"   style="max-width:90%" alt="Detailed explanation of .net mvc+layui for uploading pictures and texts" >
                    <p id="demoText"></p>
                </div>
            </div>
        </div>          
   </div>
</body>
</html>
<script type="text/javascript">
    layui.use(&#39;upload&#39;, function () {
        var $ = layui.jquery;
        var upload = layui.upload;
        //普通图片上传
        var uploadInst = upload.render({
            elem: &#39;#test1&#39;,
            url: &#39;@Url.Action("Upload","ImageUpload")&#39;, //上传地址,后台的某个控制器
            before: function (obj) {
                obj.preview(function (index, file, result) {
                    $(&#39;#demo1&#39;).attr(&#39;src&#39;, result);
                });
            }, //长传之前执行的代码,将需要上传的图片显示在页面上
            done: function (res) {
                if (res.Result) {

                }
            }, //上传成功后的回传数据,后台代码未编写,此处尚为写任何内容,将在后面的内容中补上
            error: function () {
                //演示失败状态,并实现重传
                var demoText = $(&#39;#demoText&#39;);
                demoText.html(&#39;<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>&#39;);
                demoText.find(&#39;.demo-reload&#39;).on(&#39;click&#39;, function () {
                    uploadInst.upload();
                });
            }
        });
    });
</script>

三、后台代码及前端代码完善

 接下来在上面代码所示的后台链接()中编写图片上传代码:

下面先贴出代码,然后再讲解上传思路:

ImageUploadController.cs

/// <summary>
 /// 上传图片
 /// </summary>
 /// <returns></returns>
 public ActionResult Upload()
 {
     try
     {
         HttpFileCollectionBase files = Request.Files;
         HttpPostedFileBase file = files[0];
         //获取文件名后缀
         string extName = Path.GetExtension(file.FileName).ToLower();
         //获取保存目录的物理路径
         if (System.IO.Directory.Exists(Server.MapPath("/Images/")) == false)//如果不存在就创建images文件夹
         {
             System.IO.Directory.CreateDirectory(Server.MapPath("/Images/"));
         }
         string path = Server.MapPath("/Images/"); //path为某个文件夹的绝对路径,不要直接保存到数据库
     //    string path = "F:\\TgeoSmart\\Image\\";
         //生成新文件的名称,guid保证某一时刻内图片名唯一(文件不会被覆盖)
         string fileNewName = Guid.NewGuid().ToString();
         string ImageUrl = path + fileNewName + extName;
         //SaveAs将文件保存到指定文件夹中
         file.SaveAs(ImageUrl);
         //此路径为相对路径,只有把相对路径保存到数据库中图片才能正确显示(不加~为相对路径)
         string url = "\\Images\\" + fileNewName + extName;
         return Json(new
         {
             Result = true,
             Data = url
         });
     }
     catch (Exception exception)
     {
         return Json(new
         {
             Result = false,
             exception.Message
         });
     }
 }

上面一段代码里有详细的注释信息,这里需要注意的是,我们保存图片的路径的问题。

Server.MapPath()函数获取的是某个文件夹的绝对路径,关于这个函数的一些用法我百度一份截图贴在这里:

Detailed explanation of .net mvc+layui for uploading pictures and texts

Server.MapPath()获取的是图片的绝对路径,而实际调用图片时,考虑到网站安全性问题,浏览器并不允许我们的页面使用绝对路径去获取图片资源,因此,在数据库中保存的路径只能是相对路径,也就是代码中这一句的作用:

Detailed explanation of .net mvc+layui for uploading pictures and texts

上面代码中,我并没有直接保存imageUrl到数据库中,另外生成一个相对路径保存图片,原因就是这个。

下面给出完整的前端代码,包括图片上传的改进和所有信息的保存:

@{
    Layout = "../Shared/_TopLayout.cshtml";
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div id="picUpload">
<!--新增代码,添加信息保存按钮-->
        <div class="layui-form-item sel-fixed-right">
            <div class="layui-input-block">
                <input type="button" class="layui-btn layui-btn-small layui-btn-normal" value="保存" onclick="saveInfo()" />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">图片标题</label>
            <div class="layui-input-block" style="width: 554px; position: relative;">
                <input type="text" name="ImageTitle" lay-verify="required" placeholder="图片标题" autocomplete="off" class="layui-input" id="iTitle">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block" style="width: 554px; position: relative;">
                <textarea placeholder="请输入内容" class="layui-textarea" name="Remark" id="iRemark"></textarea>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-upload">
                <label class="layui-form-label">上传图片</label>
                <button type="button" class="layui-btn" id="test1">上传图片</button>
                <div class="layui-upload-list">
                    <label class="layui-form-label">图片上传前展示</label>
                    <img  class="layui-upload-img" id="demo1"   style="max-width:90%" alt="Detailed explanation of .net mvc+layui for uploading pictures and texts" >
                    <p id="demoText"></p>                  
                </div>
<!--新增代码,上传后图片显示 -- >
                <div class="layui-upload-list">
                    <label class="layui-form-label">图片上传后展示</label>
                    <img  class="layui-upload-img" id="demo2"   style="max-width:90%" alt="Detailed explanation of .net mvc+layui for uploading pictures and texts" >
                </div>
            </div>
       </div>
    </div>
</body>
</html>
<script type="text/javascript">
    var imageUrl;//新增代码,保存上传图片后回传的图片路径

    layui.use(&#39;upload&#39;, function () {
        var $ = layui.jquery;
        var upload = layui.upload;
        //普通图片上传
        var uploadInst = upload.render({
            elem: &#39;#test1&#39;,
            url: &#39;@Url.Action("Upload","ImageUpload")&#39;,
            before: function (obj) {
                obj.preview(function (index, file, result) {
                    $(&#39;#demo1&#39;).attr(&#39;src&#39;, result);
                });
            },
            done: function (res) {
                if (res.Result) {
          //新增代码,将回传的图片保存路径进行保存并将图片绑定到上传后图片展示处
                    imageUrl = res.Data;
                    $("#demo2").attr("src", imageUrl);
                }
            },
            error: function () {
                //演示失败状态,并实现重传
                var demoText = $(&#39;#demoText&#39;);
                demoText.html(&#39;<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>&#39;);
                demoText.find(&#39;.demo-reload&#39;).on(&#39;click&#39;, function () {
                    uploadInst.upload();
                });
            }
        });
    });

//新增代码,将完整的信息传到后台保存
    var saveInfo = function () {
        $.ajax({
            type: &#39;post&#39;,
            url: &#39;@Url.Action("Save", "ImageUpload")&#39;,
            dataType: &#39;json&#39;,
            data: {
                title: $("#iTitle").val(),
                remark: $("#iRemark").val(),
                url:imageUrl
            },
            success: function (res) {
                if (res.Result) {
                    alert("保存成功");
                }
            }
        });
    }
</script>

然后,补齐后端信息保存的代码:

public ActionResult Save(string title,string remark,string url)
 {
     try
     {
         var imageInfo = new ImageInfo() {
             Id = Guid.NewGuid(),
             Name = title,
             Url = url,
             Remark = remark,
             UploadTime = DateTime.Now.ToLocalTime()
         };
         context.ImageInfos.Add(imageInfo);
         context.SaveChanges();
         return Json(new{
             Result = true
         });

     } catch (Exception exception)
     {
         return Json(new {
             Result = true,
             exception.Message
         });
     }
 }

下面展示一下页面:

Detailed explanation of .net mvc+layui for uploading pictures and texts

然后看一下数据库里的信息:

Detailed explanation of .net mvc+layui for uploading pictures and texts再看一下我们对应的图片保存的位置:

Detailed explanation of .net mvc+layui for uploading pictures and texts

Detailed explanation of .net mvc+layui for uploading pictures and texts

更多layui知识请关注layui使用教程栏目。

The above is the detailed content of Detailed explanation of .net mvc+layui for uploading pictures and texts. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete