• 六、图片上传


    一、图片上传和文件上传

    后台代码:

            //上传图片
            [HttpPost]
            public async Task<IActionResult> UploadImage([FromForm(Name = "file")] IFormFile file, string name, string password)
            {
                string url = string.Empty;
                try
                {
                    DbContext db = new DbContext();
    
                    Users user = db.Db.Queryable<Users>().Where(p => p.UserName == name).First();
                    //T_AccountModel userAccount = db.Db.Context..FirstOrDefault(t => t.UserName == Account);
                    if (user != null)
                    {
                        return Json(new { State = false, Code = 0, Msg = "该用户名已被注册!", Time = DateTime.Now.ToString() });
                    }
                    //图片上传
                    string date = DateTime.Now.ToString("yyyy-MM-dd");
                    url = "/Upload/" + date + "/";
                    string path = Path.Combine(Environment.CurrentDirectory, "Upload", date);
                    if (!System.IO.Directory.Exists(path))//判断上传路径是否存在
                    {
                        System.IO.Directory.CreateDirectory(path);
                    }
                    string filePath = string.Empty;
                    string fileName = string.Empty;
                    if (file.Length > 0)
                    {
                        //定义图片数组后缀格式
                        string[] LimitPictureType = { ".JPG", ".JPEG", ".GIF", ".PNG", ".BMP" };
                        string fileFormat = System.IO.Path.GetExtension(file.FileName).ToUpper();//获取文件后缀格式
                        if (LimitPictureType.Contains(fileFormat))
                        {
                            fileName = Guid.NewGuid().ToString("n") + fileFormat;
                            filePath = Path.Combine(path, fileName);//中间处理为唯一格式文件
                            url = url + fileName;
                            using (var stream = new FileStream(filePath, FileMode.Create))
                            {
                                try
                                {
                                    //保存文件
                                    await file.CopyToAsync(stream);
                                }
                                catch (Exception ex)
                                {
                                    return Json(new { State = false, data = new { src = url }, Code = 0, Msg = "文件保存失败!", Time = DateTime.Now.ToString() });
                                }
                            }
                        }
                        else
                        {
                            return Json(new { State = false, Code = 0, Msg = "请上传指定格式的图片!", Time = DateTime.Now.ToString() });
                        }
                    }
    
                    //
                }
                catch (Exception e)
                {
                    Trace.WriteLine("异常:" + e);
                }
                return Json(new { State = false, Code = 0, data = new { src = url }, Msg = "图片上传成功!", Time = DateTime.Now.ToString() });
            }
    
    
            //上传文件
            [HttpPost]
            public async Task<IActionResult> UploadFile([FromForm(Name = "file")] IFormFile file, string name, string password)
            {
                string url = string.Empty;
                try
                {
                    DbContext db = new DbContext();
    
                    Users user = db.Db.Queryable<Users>().Where(p => p.UserName == name).First();
                    //T_AccountModel userAccount = db.Db.Context..FirstOrDefault(t => t.UserName == Account);
                    if (user != null)
                    {
                        return Json(new { State = false, Code = 0, Msg = "该用户名已被注册!", Time = DateTime.Now.ToString() });
                    }
                    //文件上传
                    string date = DateTime.Now.ToString("yyyy-MM-dd");
                    url = "/Upload/" + date + "/";
                    string path = Path.Combine(Environment.CurrentDirectory, "Upload", date);
                    if (!System.IO.Directory.Exists(path))//判断上传路径是否存在
                    {
                        System.IO.Directory.CreateDirectory(path);
                    }
                    string filePath = string.Empty;
                    string fileName = string.Empty;
                    if (file.Length > 0)
                    {
                        string fileFormat = System.IO.Path.GetExtension(file.FileName).ToUpper();//获取文件后缀格式
                        fileName = Guid.NewGuid().ToString("n") + fileFormat;
                        filePath = Path.Combine(path, fileName);//中间处理为唯一格式文件
                        url = url + fileName;
                        using (var stream = new FileStream(filePath, FileMode.Create))
                        {
                            try
                            {
                                //保存文件
                                await file.CopyToAsync(stream);
                            }
                            catch (Exception ex)
                            {
                                return Json(new { State = false, data = new { src = url }, Code = 0, Msg = "文件保存失败!", Time = DateTime.Now.ToString() });
                            }
                        }
    
                    }
                    //
                }
                catch (Exception e)
                {
                    Trace.WriteLine("异常:" + e);
                }
                return Json(new { State = false, Code = 0, data = new { src = url,name= file.FileName}, Msg = "图片上传成功!", Time = DateTime.Now.ToString() });
            }

    前台代码

                        //上传图片接口(返回的数据格式见下文),若不开启图片上传,剔除该项即可
                        uploadImage: {
                            url: '/LayIM/UploadImage', //接口地址
                            type: 'post' //默认post
                        },
                        //上传文件接口(返回的数据格式见下文),若不开启文件上传,剔除该项即可
                        uploadFile: {
                            url: '/LayIM/UploadFile', //接口地址
                            type: 'post' //默认post
                        },
                        //扩展工具栏,下文会做进一步介绍(如果无需扩展,剔除该项即可)
                        tool: [{
                            alias: 'code', //工具别名
                            title: '代码', //工具名称
                            icon: '&#xe64e;' //工具图标,参考图标文档
                        }],

    监听工具栏

                    //监听自定义工具栏点击,以添加代码为例
                    layim.on('tool(code)', function (insert, send, obj) { //事件中的tool为固定字符,而code则为过滤器,对应的是工具别名(alias)
                        layer.prompt({
                            title: '插入代码'
                            , formType: 2
                            , shade: 0
                        }, function (text, index) {
                            layer.close(index);
                            insert('[pre class=layui-code]' + text + '[/pre]'); //将内容插入到编辑器,主要由insert完成
                            //send(); //自动发送
                        });
                        console.log(this); //获取当前工具的DOM对象
                        console.log(obj); //获得当前会话窗口的DOM对象、基础信息
                    }); 
                    //ready内结束
    点到为止
  • 相关阅读:
    b_jd_水坑数量(向外流dfs)
    b_wy_购买商品使得满减最省(01背包)
    b_wy_最优路径(构造树+dfs)
    Redis:List列表相关指令
    Redis:String字符串常用指令
    Redis:linux基本的指令
    Redis:redis-benchmark性能测试/压力测试
    Redis:增大并发量的演进过程
    Kafka的下载安装和测试,及消费端数据中文乱码问题
    Git:常用命令
  • 原文地址:https://www.cnblogs.com/fger/p/11834064.html
Copyright © 2020-2023  润新知