做电子商务网站遇到图片上传问题。基本上我所有的产品信息都传递到数据库,除了图像文件。好像无法读取。这是我的方法:
[HttpPost]
[Route("/create_product")]
public async Task<IActionResult> productAdd(ProductCheck check)
{
int? id = HttpContext.Session.GetInt32("userId");
if(id == null)
{
return RedirectToAction("LoginPage", "User");
}
else
{
if(ModelState.IsValid)
{
User exists = _context.Users.Where(u=>u.UserId == id).SingleOrDefault();
Product newProduct = new Product
{
Title = check.Title,
Description = check.Description,
Price = check.Price,
UserId = (int)id,
CreatedAt = DateTime.Now,
};
var uploadDestination = Path.Combine(_hostingEnvironment.WebRootPath, "uploaded_images");
if (check.Image != null)
{
var filepath = Path.Combine(uploadDestination, check.Image.FileName);
using (var fileStream = new FileStream(filepath, FileMode.Create))
{
await check.Image.CopyToAsync(fileStream);
newProduct.Picture = "/uploaded_images/" + check.Image.FileName;
}
}
_context.Add(newProduct);
_context.SaveChanges();
}
else
{
TempData["error"] = "Not added. Error";
}
return RedirectToAction("Homepage");
我之前遇到的错误是:Image
这是我的模型:
using System;
使用 System.Collections.Generic;
命名空间 sellwalker.Models { 公共(public)类产品:BaseEntity {
public int ProductId{get;set;}
public string Title{get;set;}
public string Description{get;set;}
public decimal Price{get;set;}
public string Picture { get; set; }
public DateTime CreatedAt{get;set;}
public List<Order> Orders {get; set;}
public Product()
{
Orders = new List<Order>();
}
public int UserId{get;set;}
public User Seller{get;set;}
}
和ViewModel验证表:
public class ProductCheck : BaseEntity
{
[Required]
[MinLength(2, ErrorMessage="Name of the product should be greater than 2 characters")]
public string Title{get;set;}
[Required]
[MinLength(10, ErrorMessage="Description of the product should be greater than 10 characters")]
public string Description{get;set;}
[Required]
public decimal Price{get;set;}
public IFormFile Image { get; set; }
}
最佳答案
想通了!确保您的表单中包含 enctype="multipart/form-data"!
关于c# - 系统无法读取我的图片上传文件(?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48711011/