/// <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
}
代碼里面的那個取WEB目錄路徑的hostingEnv需要在控制器的構(gòu)造函數(shù)中注入一下,代碼如下:
private IHostingEnvironment hostingEnv;
public BlogController(IHostingEnvironment env)
{
this.hostingEnv = env;
}