简体   繁体   English

如何将图像文件发布到 asp.net core 5 中的 api 控制器? (415 错误)

[英]how do you post an image file to an api controller in asp.net core 5? (415 error)

I am trying to implement Filepond image uploader into my ASP.net Core 5 web application using the entity framework.我正在尝试使用实体框架将 Filepond 图像上传器实现到我的 ASP.net Core 5 Web 应用程序中。

I am having trouble saving the uploaded images to the server.我无法将上传的图像保存到服务器。

The post request to the Api controller errors with a 415 "Unsupported Media type" error.对 Api 控制器的 post 请求错误并显示 415“不支持的媒体类型”错误。

The code from the Api Controller constructor gets hit, but not the code within the Create method.来自 Api Controller 构造函数的代码被命中,但不会命中 Create 方法中的代码。

javascript file: javascript文件:

const inputElement = document.querySelector('input[type="file"]');
const pond = FilePond.create(inputElement);

FilePond.setOptions({
    server: {
        url: "/SaveImage/",
        process: (fieldName, file, metadata, load, error, progress, abort) => {
            const formData = new FormData();
            formData.append(fieldName, file, file.name);
            formData.append("CaseId", "@Model.CaseId");

            const request = new XMLHttpRequest();

            request.open('POST', '/SaveImage/');

            request.upload.onprogress = (e) => {
                progress(e.lengthComputable, e.loaded, e.total);
            };

            request.onload = function () {
                if (request.status >= 200 && request.status < 300) {
                    load(request.responseText);
                }
                else {
                    error('Error during Image Upload');
                }
            };

            request.send(formData);

            return {
                abort: () => {
                    request.abort();
                    abort();
                }
            };
        }, 
    }
})

Api Controller:接口控制器:

[Route("[controller]")]
[ApiController]
public class saveImageController : ControllerBase
{
    private readonly NoPainNoGameDbContext _context;

    public saveImageController(NoPainNoGameDbContext context)
    {
        _context = context;
    }

    [HttpPost]
    public async Task<ActionResult> Create([FromForm] Models.GameImage doc, [FromForm] List<IFormFile> files)
    {
        if (files != null && doc.CaseId != 0)
        { 
            foreach (var file in files)
            {
                doc.Guid = Guid.NewGuid().ToString();
                doc.ImageName = file.FileName.Split('.').FirstOrDefault();
                doc.FileType = file.FileName.Split('.').LastOrDefault().ToLower();
                doc.CreatedOn = DateTime.Now;
                doc.FileSize = file.Length;

                _context.GameImages.Add(doc);
                await _context.SaveChangesAsync();
            }

            return Ok(doc.Guid); 
        }
        else
        {
            return BadRequest("The file is null"); 
        }
    }
}

Input输入

    <input type="file" multiple class="filepond" id="imageUploader" name="files">

I've never used FilePond before but I managed to reproduce your problem with the code you provided.我以前从未使用过 FilePond,但我设法用您提供的代码重现了您的问题。 All you need to do is use the [FromForm] attribute on your action parameters ie您需要做的就是在操作参数上使用[FromForm]属性,即

public async Task<ActionResult> Create([FromForm] Models.GameImage doc, [FromForm] List<IFormFile> files)

You haven't provided what your input[type='file'] looks like, but it should also have a name attribute that matches the action parameter files ( List<IFormFile> files ), ie your input[type='file] should have a name='files' attribute (if it doesn't already).您尚未提供input[type='file']外观,但它也应该具有与操作参数filesList<IFormFile> files )匹配的name属性,即您的input[type='file]应该有一个name='files'属性(如果还没有)。

Also, I wouldn't suggest passing your entities as an action parameter, it tends to become problematic as your project progresses.此外,我不建议将您的实体作为操作参数传递,随着您的项目进展,它往往会出现问题。 Instead you should use a DTO, What is a Data Transfer Object (DTO)?相反,您应该使用 DTO,什么是数据传输对象 (DTO)?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Asp.net core api 从 Javascript 得到“415 Unsupported Media Type”错误,而不是 Postman - Asp.net core api getting “415 Unsupported Media Type” error from Javascript, not Postman 从 ASP.NET Core API 端点获取不支持的媒体类型的 HttpCode 415 错误 - Getting HttpCode 415 error of Unsupported media type from ASP.NET Core API endpoint 访问asp.net核心控制器中图像控件上显示的文件 - Accessing file displayed on image control in the controller in asp.net core ASP.Net Core 3 和简单的 POST controller - ASP.Net Core 3 and simple POST the controller How to POST javascript object, javascript object list and file list to asp.net core controller - How to POST javascript object, javascript object list and file list to asp.net core controller 如何向ASP.Net Core API控制器提交表单 - How to submit a form to an ASP.Net Core API Controller 如何从 AJAX 上传文件到 asp.net 核心控制器 - How to upload file from AJAX to asp.net core controller jQuery发布不会将数据发布到ASP.NET API控制器 - jQuery post wont post data to ASP.NET API Controller 如何将文件发布到 ASP.NET Web api - How can I post file to ASP.NET Web api 无法在asp.net核心中使用ajax将json发布到控制器 - Cannot post json to controller using ajax in asp.net core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM