【发布时间】:2021-11-28 02:44:58
【问题描述】:
public class ImageModel
{
[Key]
public int ImageId { get; set; }
[Column(TypeName = "nvarchar(50)")]
public string Title { get; set; }
[Column(TypeName = "nvarchar(100)")]
[DisplayName("Image Name")]
public string ImageName { get; set; }
[NotMapped]
[DisplayName("Upload File")]
public IFormFile ImageFile { get; set; }
}
这是我用于发布请求的控制器类 我创建了一个 wwwroot 文件夹来保存图片
[Route("api/[Controller]")]
[ApiController]
public class ImageController : Controller
{
private readonly Databasecontext _context;
private readonly IWebHostEnvironment _hostEnvironment;
public ImageController(Databasecontext context, IWebHostEnvironment hostEnvironment)
{
_context = context;
this._hostEnvironment = hostEnvironment;
}
// GET: Image
public async Task<IActionResult> Index()
{
return View(await _context.Images.ToListAsync());
}
// GET: Image/Create
public IActionResult Create()
{
return View();
}
// POST: Image/Create
[HttpPost]
public async Task<IActionResult> Create([Bind("ImageId,Title,ImageName")] ImageModel imageModel)
{
if (ModelState.IsValid)
{
//Save image to wwwroot/image
string wwwRootPath = _hostEnvironment.WebRootPath;
string fileName = Path.GetFileNameWithoutExtension(imageModel.ImageFile.FileName);
string extension = Path.GetExtension(imageModel.ImageFile.FileName);
imageModel.ImageName = fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
string path = Path.Combine(wwwRootPath + "/Image/", fileName);
using (var fileStream = new FileStream(path, FileMode.Create))
{
await imageModel.ImageFile.CopyToAsync(fileStream);
}
//Insert record
_context.Add(imageModel);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(imageModel);
}
这是我的数据库上下文
public DbSet<ImageModel> Images { get; set; }
我只需要使用邮递员对此进行测试并将其与 angular 结合使用。有人能帮我吗? 当我通过邮递员发送图像时出现此错误请求实体的媒体类型不支持服务器或资源不支持。
【问题讨论】:
-
嗨@scorpion private,你能分享一下你是如何在Postman中发布数据的吗?我无法重现该问题并将数据成功发布到行动。
-
我已经添加了上面邮递员的输出
-
我通过发送 base64 和文件名来执行该功能,当 API 接收到 base64 时,它将其转换为 IFormFile 并将其复制到预定义的目录
-
你能给我示例代码吗@Juan_H
-
嗨@scorpionprivate,我的回答是否帮助您解决了您的问题?如果是这样,你能接受作为答案吗?如果没有,你能跟进让我知道吗?参考:How to accept as answer。谢谢。
标签: mysql entity-framework asp.net-core file-upload ef-code-first-mapping