ASP.NET COREでLayUIエディタで画像をアップロードする方法
1957 ワード
///
/// 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; }