//[FromServices]IHostingEnvironment environment public async Task <IActionResult> OnPostUpload(IFormFileCollection files) { try { string username = HttpContext.Session.GetString("UserName"); if (string.IsNullOrEmpty(username)) { return(Ok(new { success = true, code = 0 })); } files = Request.Form.Files; List <TmpUrl> list = new List <TmpUrl>(); string destinationDir = "/var/www/VueApp/static/img";// /var/www/VueApp/static/img foreach (var formFile in files) { if (formFile.Length > 0) { if (!string.IsNullOrEmpty(destinationDir)) { Directory.CreateDirectory(destinationDir); } var fileName = Guid.NewGuid().ToString() + ".jpg"; var path = Path.Combine(destinationDir, fileName); using (var stream = new FileStream(path, FileMode.CreateNew)) { await formFile.CopyToAsync(stream); TmpUrl tu = new TmpUrl(); tu.Url = @"/static/img/" + fileName; // /static/img/ list.Add(tu); } } } return(Ok(new { success = true, code = 1, data = list })); } catch (Exception ex) { loggerHelper.Error("UploadController.OnPostUpload", "异常位置:UploadController.OnPostUpload" + "异常消息:" + ex.Message); return(Ok(new { success = false, code = 0, message = ex.Message })); } }
public async Task <IActionResult> OnPostUpload() { var date = Request; var files = Request.Form.Files; if (files.Count == 0) { TmpUrl tmp = new TmpUrl() { Errno = 404, Msg = "没有图片,上传什么" }; return(new JsonResult(tmp)); } long size = files.Sum(f => f.Length); string shortTime = $"/Update/{DateTime.Now.ToString("yyyy/MM/dd")}/"; string filePhysicalPath = $@"{_host.WebRootPath}/{shortTime}"; //文件路径 可以通过注入 IHostingEnvironment 服务对象来取得Web根目录和内容根目录的物理路径 if (!Directory.Exists(filePhysicalPath)) //判断上传文件夹是否存在,若不存在,则创建 { Directory.CreateDirectory(filePhysicalPath); //创建文件夹 } List <string> urlLs = new List <string>(); foreach (var file in files) { if (file.Length > 0) { var fileName = System.Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);//文件名+文件后缀名 using (var stream = new FileStream(filePhysicalPath + fileName, FileMode.Create)) { await file.CopyToAsync(stream); } urlLs.Add($"{shortTime}{fileName}"); } } return(new JsonResult(TmpUrl.SuccessInfo("上传成功", urlLs))); }