您不需要将图像存储在字节数组中,您的模型只需要IFormFile这样的:
模型:
[Required(ErrorMessage = "The {0} field is required")]
[Display(Name = "Image")]
[DataType(DataType.Upload)]
public IFormFile Image { get; set; }
控制器:
if (model.Image == null)
return View(model);
string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath,"Your upload path");
string ImagePath = Guid.NewGuid().ToString() + "_" + model.Image.FileName;
string filePath = Path.Combine(uploadsFolder, ImagePath);
using (FileStream fs = new FileStream(filePath, FileMode.Create))
{
await model.Image.CopyToAsync(fs);
}
将此添加到您的form标签中:enctype="multipart/form-data"。它对于type="file"提交的输入至关重要。
看法:
<form enctype="multipart/form-data" Other attributes...>
<div class="custom-file">
<input asp-for="Model.Image" type="file" class="custom-file-input fileUpload" />
<label class="custom-file-label fileLabel">Choose file</label>
</div>
<input type="submit" value="Submit" />
</form>
最后,您将ImagePath 唯一的保存在您的数据库实体中。