码迷,mamicode.com
首页 > Web开发 > 详细

六、图片上传

时间:2019-11-11 13:07:22      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:post   wait   中间   too   console   开启   als   copyto   exists   

一、图片上传和文件上传

后台代码:

        //上传图片
        [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内结束

 

六、图片上传

标签:post   wait   中间   too   console   开启   als   copyto   exists   

原文地址:https://www.cnblogs.com/fger/p/11834064.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!