ASP.NET CORE中用LayUI編輯器上傳圖片的方法

   /// <summary>
    /// layui在線編輯器里的上傳圖片功能
    /// </summary>
    /// <returns></returns>
    [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 = "圖片標(biāo)題" } });
        }
        return Json(new { code = 1, msg = "上傳失敗", });
        #endregion
    }

代碼里面的那個(gè)取WEB目錄路徑的hostingEnv需要在控制器的構(gòu)造函數(shù)中注入一下,代碼如下:

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 大文件的上傳是我一直以來想學(xué)習(xí)的一個(gè)技術(shù)點(diǎn),今天在項(xiàng)目閑暇之時(shí),終于有機(jī)會(huì)自己嘗試了一把,本文僅僅是個(gè)Demo,各...
    小久代碼搬運(yùn)閱讀 2,027評(píng)論 0 1
  • Lua 5.1 參考手冊(cè) by Roberto Ierusalimschy, Luiz Henrique de F...
    蘇黎九歌閱讀 13,906評(píng)論 0 38
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,948評(píng)論 18 139
  • 本文包括:1、文件上傳概述2、利用 Commons-fileupload 組件實(shí)現(xiàn)文件上傳3、核心API——Dis...
    廖少少閱讀 12,605評(píng)論 5 91
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,766評(píng)論 18 399