我想上传我的图片。上传过程正在工作,但是当我尝试在正面显示我的图像时,它不起作用,仅呈现禁用的
<img>
标志。
ProductController.cs
:
public IActionResult Upsert(int? id)
{
ProductVM productVM = new()
{
CategoryList = _unitOfWork.Category.GetAll().Select(u => new SelectListItem
{
Text = u.Name,
Value = u.Id.ToString()
}),
Product = new Product()
};
if (id == null || id == 0)
{
// create
return View(productVM);
}
else
{
// update
productVM.Product = _unitOfWork.Product.Get(u => u.Id == id);
return View(productVM);
}
}
[HttpPost]
public IActionResult Upsert(ProductVM productVM,IFormFile? file)
{
if (ModelState.IsValid)
{
string wwwRootPath = _webHostEnvironment.WebRootPath;
if (file != null)
{
string fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
string productPath = Path.Combine(wwwRootPath, @"images\product");
using (var fileStream = new FileStream(Path.Combine(productPath, fileName),FileMode.Create))
{
file.CopyTo(fileStream);
}
productVM.Product.ImageURL = @"\images\product\" + fileName;
}
_unitOfWork.Product.Add(productVM.Product);
_unitOfWork.Save();
TempData["success"] = "Product created successfully";
return RedirectToAction("Index");
}
else
{
productVM.CategoryList = _unitOfWork.Category.GetAll().Select(u => new SelectListItem
{
Text = u.Name,
Value = u.Id.ToString()
});
return View(productVM);
}
}
Upsert.cshtml
:
<div class="col-2">
<img src="/@Model.Product.ImageURL" width="100%" style="border-radius:5px; border:1px solid #bbb9b9" />
</div>
我尝试了不同的变体,但不起作用。
我想在前端页面上显示我的产品图像,意思是
upsert.cshtml
,但图像未显示
这是路径问题,现在你的网址是
https://localhost:44382/images/productd600ce5d-ffba-4e19-be22-e7494f5f3640.jpg
错了,正确的网址应该是
https://localhost:44382/images/product/d600ce5d-ffba-4e19-be22-e7494f5f3640.jpg
所以请使用下面我修改过的示例代码来修复它。
if (ModelState.IsValid)
{
string wwwRootPath = _webHostEnvironment.WebRootPath;
if (file != null)
{
string fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
// Use Path.Combine like below
string productPath = Path.Combine(wwwRootPath, "images", "product");
using (var fileStream = new FileStream(Path.Combine(productPath, fileName), FileMode.Create))
{
file.CopyTo(fileStream);
}
// Change you path like below
productVM.Product.ImageURL = "/images/product/" + fileName;
}
_unitOfWork.Product.Add(productVM.Product);
_unitOfWork.Save();
TempData["success"] = "Product created successfully";
return RedirectToAction("Index");
}