uploading image asp.net Core

前端 未结 3 2043
挽巷
挽巷 2020-12-13 16:35

i am new to ASP.net COre and i would like to upload a file ( an image) and store it in a secific Folder. ihave been following this tuto (File uploads in ASP.NET Core) but i

3条回答
  •  抹茶落季
    2020-12-13 17:00

    You should inject IHostingEnvironment so you can get the web root (wwwroot by default) location.

    public class HomeController : Controller
    {
        private readonly IHostingEnvironment hostingEnvironment;
        public HomeController(IHostingEnvironment environment)
        {
            hostingEnvironment = environment;
        }
        [HttpPost]
        public async Task UploadFiles(List files)
        {
            long size = files.Sum(f => f.Length);
    
            // full path to file in temp location
            var filePath = Path.GetTempFileName();
    
            foreach (var formFile in files)
            {
                var uploads = Path.Combine(hostingEnvironment.WebRootPath, "images");
                var fullPath = Path.Combine(uploads, GetUniqueFileName(formFile.FileName));
                formFile.CopyTo(new FileStream(fullPath, FileMode.Create));
    
            }
            return Ok(new { count = files.Count, size, filePath });
        }
        private string GetUniqueFileName(string fileName)
        {
            fileName = Path.GetFileName(fileName);
            return  Path.GetFileNameWithoutExtension(fileName)
                      + "_" 
                      + Guid.NewGuid().ToString().Substring(0, 4) 
                      + Path.GetExtension(fileName);
        }
    }
    

    This will save the files to the images directory in wwwroot.

    Make sure that your form tag's action attribute is set to the UploadFiles action method of HomeController(/Home/UploadFiles)

    Upload one or more files using this form:

    I am not very certain why you want to return Ok result from this. You may probably return a redirect result to the listing page.

提交回复
热议问题