进行电子商务网站并解决图片上传问题。基本上我的所有产品信息都传递到数据库,除了图像文件。看起来无法阅读。这是我的方法:
[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");
这是我的模特:
using System;
使用System.Collections.Generic;
命名空间sellwalker.Models { 公共类产品: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; }
}
答案 0 :(得分:0)
想通!请确保您的形式为enctype =“multipart / form-data”