[英]Upload picture to SQL Server database using Entity Framework in ASP.NET MVC
I have been trying to upload pictures to a SQL Server database by using Entity Framework.我一直在尝试使用实体框架将图片上传到 SQL 服务器数据库。
I tried to take the picture and convert it from IFormFile
in the DtoModel to byte[]
in the primary model to store it in the database but it doesn't work and I get an "invalid value".我尝试拍摄照片并将其从IFormFile
中的 IFormFile 转换为主要 model 中的byte[]
以将其存储在数据库中,但它不起作用,我得到一个“无效值”。
I used this logical method in the ASP.NET Web API many times and it's working smoothly, so I can't figure out what I miss here.我在 ASP.NET Web API 中多次使用这种逻辑方法并且它工作顺利,所以我无法弄清楚我在这里错过了什么。
Primary model:初级 model:
[Key]
public int Id { get; set; }
public string Name { get; set; }
[Required(ErrorMessage = "Photo is required.")]
public byte[] Pic { get; set; }
public string PicFromat { get; set; }
DtoModel:模型:
public string Name { get; set; }
public IFormFile Pics { get; set; }
Controller: Controller:
private readonly ApplicationDbContext _context;
private new List<string> _allowedExtenstions = new List<string> { ".jpg", ".png" };
private long _maxAllowedPosterSize = 1048576;
public propertiesController(ApplicationDbContext context)
{
_context = context;
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create( dtoprop model)
{
if (!ModelState.IsValid)
{
return View( model);
}
if(!_allowedExtenstions.Contains(Path.GetExtension(model.Pics.FileName.ToLower())))
{
ModelState.AddModelError("Pic", "Only .PNG, .JPG images are allowed!");
return View(model);
}
if (model.Pics.Length > _maxAllowedPosterSize)
{
ModelState.AddModelError("Pic", "Poster cannot be more than 1 MB!");
return View(model);
}
using var dataStream = new MemoryStream();
await model.Pics.CopyToAsync(dataStream);
var pic = new property
{
Name = model.Name,
Pic = dataStream.ToArray()
};
_context.Properties.Add(pic);
_context.SaveChanges();
return RedirectToAction("Index");
}
The Create.cshtml
: Create.cshtml
:
@model EshopTest5.Data.dtoprop
@{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>property</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PicFromat" class="control-label"></label>
<input asp-for="PicFromat" class="form-control" />
<span asp-validation-for="PicFromat" class="text-danger"></span>
</div>
<div class="custom-file">
<input type="file" class="custom-file-input" asp-for="Pic" accept=".png, .jpg" />
<label class="custom-file-label" asp-for="Pic"></label>
<span asp-validation-for="Pic" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
I personally would advice you add a client side validation for _allowedExtenstions
not a server side validation so the user does not waste his/her data bundle posting the formdata to the server only to get back a validation error我个人建议您为_allowedExtenstions
添加客户端验证而不是服务器端验证,这样用户就不会浪费他/她的数据包将表单数据发布到服务器只是为了返回验证错误
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create( dtoprop model)
{
if (!ModelState.IsValid)
{
return View( model);
}
var stream = new MemoryStream();
model.Pics.File.CopyTo(stream);
stream.Position = 0;
var byteData = stream.ToArray();
var pic = new property
{
Name = model.Name,
Pic = byteData
};
_context.Properties.Add(pic);
_context.SaveChanges();
return RedirectToAction("Index");
}
and you should add enctype="multipart/form-data" method="post"
to your html form.您应该将enctype="multipart/form-data" method="post"
添加到您的 html 表单中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.