ASP.NET CORE中用LayUI编辑器上传图片的方法

   /// 
    /// layui在线编辑器里的上传图片功能
    /// 
    /// 
    [HttpPost]
    public IActionResult UploadImage()
    {
        #region 文件上传
        var imgFile = Request.Form.Files[0];
        if (imgFile != null && !string.IsNullOrEmpty(imgFile.FileName))
        {
            long size = 0;
            string tempname = "";
            var filename = ContentDispositionHeaderValue
                            .Parse(imgFile.ContentDisposition)
                            .FileName
                            .Trim('"');
            var extname = filename.Substring(filename.LastIndexOf("."), filename.Length - filename.LastIndexOf("."));
            var filename1 = System.Guid.NewGuid().ToString().Substring(0, 6) + extname;
            tempname = filename1;
            var path = hostingEnv.WebRootPath;
            string dir = DateTime.Now.ToString("yyyyMMdd");
            if (!System.IO.Directory.Exists(hostingEnv.WebRootPath + $@"\upload\{dir}"))
            {
                System.IO.Directory.CreateDirectory(hostingEnv.WebRootPath + $@"\upload\{dir}");
            }
            filename = hostingEnv.WebRootPath + $@"\upload\{dir}\{filename1}";
            size += imgFile.Length;
            using (FileStream fs = System.IO.File.Create(filename))
            {
                imgFile.CopyTo(fs);
                fs.Flush();
            }
            return Json(new { code = 0, msg = "上传成功", data = new { src = $"/upload/{dir}/{filename1}", title = "图片标题" } });
        }
        return Json(new { code = 1, msg = "上传失败", });
        #endregion
    }

代码里面的那个取WEB目录路径的hostingEnv需要在控制器的构造函数中注入一下,代码如下:

private IHostingEnvironment hostingEnv;
public BlogController(IHostingEnvironment env)
{
this.hostingEnv = env;
}

你可能感兴趣的:(ASP.NET CORE中用LayUI编辑器上传图片的方法)