项目场景:
.net core 7 图片上传
本来以为前面有asp的理解这块应该不成问题,但还是花费了两天时间,期间看了下官方的文档(官方文档core上传)才解决
1.这是我的模型
2.控制器
public async Task<IActionResult> Create([Bind("Id,Name,Price,SpeciesId,PhotoUrl")] Gifts gifts, IFormFile input)
{
try {
using (var memoryStream = new MemoryStream())
{
await input.CopyToAsync(memoryStream);
{
if (memoryStream.Length < 2097152)
{
gifts.PhotoUrl = memoryStream.ToArray();
}
}
}
if (ModelState.IsValid)
{
_context.Add(gifts);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
else
{
ViewData["SpeciesId"] = new SelectList(_context.giftSpecies, "Id", "Name", gifts.SpeciesId);
return View(gifts);
}
}
catch
{
ViewData["SpeciesId"] = new SelectList(_context.giftSpecies, "Id", "Id", gifts.SpeciesId);
return View(gifts);
}
}
views
greate
Index