ASP.NET Core 3.1 - Upload an image

上傳圖片 snippets

                // get the image 
                var files = HttpContext.Request.Form.Files;

                if (files != null)
                {
                    string uploadFolder = Path.Combine(_hostingEnvironment.WebRootPath, @"img");
                    // create an unique file name using guid and the file
                    string uniqueFileName = Guid.NewGuid().ToString() + files[0].FileName;
                    string filePath = Path.Combine(uploadFolder, uniqueFileName);

                    using (var fileStream = new FileStream(filePath, FileMode.Create))
                    {
                        await files[0].CopyToAsync(fileStream);
                        product.Photo = uniqueFileName;
                    }
                }

在要上傳的 form 加上 enctype=”multipart/form-data”, 要不然會有 bug

留言

這個網誌中的熱門文章

ASP.NET Web API - DTOs

Scaffold Identity into the Current Project

Passing data from controller to the view