正在 asp.net 核心中上传图像 api

uploading an image api in asp.net core

我正在构建一个 api 来存储图像作为机器模型的一部分 class 以在 xamarin.forms 中使用它所以这就是机器 class :

 public class Machine
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public string Machine_Qr { get; set; }
        public string Machine_Name { get; set; }
        [NotMapped]
        public string Image { get; set; }
}

这是机器控制器:

public class MachineController : ControllerBase
    {
        private readonly DataContext _context;
        private IHostingEnvironment _hostingEnvironment;

        public MachineController(DataContext context, IHostingEnvironment environment)
        {
            _context = context;
            _hostingEnvironment = environment ?? throw new ArgumentNullException(nameof(environment));



        }
        [HttpPost]
        public async Task<ActionResult<Machine>> Create(Machine machine)
        {
            if (ModelState.IsValid)
            {
                var files = HttpContext.Request.Form.Files;
                foreach (var Image in files)
                {
                    if (Image != null && Image.Length > 0)
                    {

                        var file = Image;
                        var uploads = Path.Combine(_hostingEnvironment.WebRootPath, "uploads\img\Machines");

                        if (file.Length > 0)
                        {
                            var fileName = ContentDispositionHeaderValue.Parse
                                (file.ContentDisposition).FileName.Trim('"');

                            System.Console.WriteLine(fileName);
                            using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
                            {
                                await file.CopyToAsync(fileStream);
                                machine.Image = file.FileName;
                            }


                        }
                    }
                }

                _context.Add(machine);
                await _context.SaveChangesAsync();

            }
            return CreatedAtAction(nameof(PostMachine), new { id = machine.Machine_Qr }, machine);
        }

但是当我试图大摇大摆地测试 api 时,我收到了这条消息:

System.InvalidOperationException: Incorrect Content-Type: application/json
   at Microsoft.AspNetCore.Http.Features.FormFeature.ReadForm()
   at Microsoft.AspNetCore.Http.DefaultHttpRequest.get_Form()
   at WebApi.Controllers.MachineController.Create(Machine machine) in C:\Users\amyra\source\repos\WebApi\Controllers\MachineController.cs:line 35

machineController 第 35 行是:

 var files = HttpContext.Request.Form.Files;

您应该在 Machine class

中收到 IFormFile 属性 的图像
[NotMapped]
public IFormFile Image { get; set; }

然后在您的请求中使用 [FromForm] 属性

[HttpPost]
public async Task<ActionResult<Machine>> Create([FromForm] Machine machine)

现在您可以删除这些行

var files = HttpContext.Request.Form.Files;
                foreach (var Image in files)
                {
                    
                }

并直接使用您通过 Swagger

上传的 machine.Image
var file = machine.Image;
if (file != null && file.Length > 0)
{
    var fileName = ContentDispositionHeaderValue.Parse
                                
    (file.ContentDisposition).FileName.Trim('"');

    System.Console.WriteLine(fileName);
    using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
        {
             await file.CopyToAsync(fileStream);
        }
}