Asp.Net Core 3.1 MVC 如何上传项目中的照片?
Asp.Net Core 3.1 MVC How to upload photos in the project?
Asp.Net Core 3.1 MVC 在我的项目中,用户需要上传一张照片,我想把照片保存在wwwroot/database下。在数据库中,只需要照片的路径,但每次我的 IFromfile 对象都为空。从现在开始谢谢你
您可以按照以下步骤完成。
创建模型Image
:
public class Image
{
public int Id { get; set; }
public string Path { get; set; }
}
在您的 wwwroot
下创建文件夹 Images
索引查看代码:
@model Image
<form asp-controller="Home" asp-action="Index" method="post" enctype="multipart/form-data">
<input type="file" name="uploadFile" class="form-control" />
<input type="submit" value="submit" id="sub" />
</form>
控制器:
public class HomeController : Controller
{
private readonly ApplicationDbContext _context;
private readonly IWebHostEnvironment _hostingEnvironment;
public HomeController(ApplicationDbContext context, IWebHostEnvironment hostingEnvironment)
{
_context = context;
_hostingEnvironment = hostingEnvironment;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public async Task<IActionResult> IndexAsync(Image image,IFormFile uploadFile)
{
if (uploadFile != null && uploadFile.Length > 0)
{
var fileName = Path.GetFileName(uploadFile.FileName);
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images", fileName);
image.Path = filePath;
_context.Images.Add(image);
_context.SaveChanges();
using (var fileSrteam = new FileStream(filePath, FileMode.Create))
{
await uploadFile.CopyToAsync(fileSrteam);
}
}
return View();
}
结果:
Asp.Net Core 3.1 MVC 在我的项目中,用户需要上传一张照片,我想把照片保存在wwwroot/database下。在数据库中,只需要照片的路径,但每次我的 IFromfile 对象都为空。从现在开始谢谢你
您可以按照以下步骤完成。
创建模型
Image
:public class Image { public int Id { get; set; } public string Path { get; set; } }
在您的
下创建文件夹wwwroot
Images
索引查看代码:
@model Image <form asp-controller="Home" asp-action="Index" method="post" enctype="multipart/form-data"> <input type="file" name="uploadFile" class="form-control" /> <input type="submit" value="submit" id="sub" /> </form>
控制器:
public class HomeController : Controller { private readonly ApplicationDbContext _context; private readonly IWebHostEnvironment _hostingEnvironment; public HomeController(ApplicationDbContext context, IWebHostEnvironment hostingEnvironment) { _context = context; _hostingEnvironment = hostingEnvironment; } public IActionResult Index() { return View(); } [HttpPost] public async Task<IActionResult> IndexAsync(Image image,IFormFile uploadFile) { if (uploadFile != null && uploadFile.Length > 0) { var fileName = Path.GetFileName(uploadFile.FileName); var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images", fileName); image.Path = filePath; _context.Images.Add(image); _context.SaveChanges(); using (var fileSrteam = new FileStream(filePath, FileMode.Create)) { await uploadFile.CopyToAsync(fileSrteam); } } return View(); }
结果: