简体   繁体   English

支持.NET Core Web API 上传图片文件

[英]Support image file upload in .NET Core Web API

I'm developing a Web API with .Net Core, where I need to allow a client to upload a list of files (mostly images) and save them to the server.我正在使用 .Net Core 开发 Web API,我需要允许客户端上传文件列表(主要是图像)并将它们保存到服务器。

The problem is that when the image is uploaded, and I try to open it from the folder where it was saved, it seems like it's corrupted and its size is not the same as the initial one.问题是当图像上传时,我尝试从保存它的文件夹中打开它,它似乎已损坏并且其大小与初始大小不同。

Here is the code of my controller:这是我的控制器的代码:

[Route("api/TestUpload")]
[Consumes("multipart/form-data")]
public class TestUploadController : Controller
{
    private readonly IHostingEnvironment _env;
    private readonly ApplicationContext _context;

    public TestUploadController(ApplicationContext context, IHostingEnvironment env)
    {
        _context = context;
        _env = env;
    }

    // GET: /<controller>/
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost("upload")]
    public async Task<IActionResult> Post([FromForm]IList<IFormFile> files)
    {
        long size = files.Sum(f => f.Length);

        var uploads = Path.Combine(_env.WebRootPath, "uploads");

        foreach (var formFile in files)
        {
            if (formFile.Length > 0)
            {
                var filePath = Path.Combine(uploads, formFile.FileName);
                using (var fileStream = new FileStream(Path.Combine(uploads, formFile.FileName), FileMode.Create))
                {
                    await formFile.CopyToAsync(fileStream);
                    fileStream.Flush();
                }
            }
        }

        return Ok(new { size });
    }
}

The only files that seem to be uploaded and saved fine are text and html files.似乎可以正常上传和保存的唯一文件是文本和 html 文件。 I've tried with a single file instead of a list, same thing.我试过用一个文件而不是一个列表,同样的事情。

I've tried several code variations and none seem to work, I'm probably doing something wrong but I just can't figure out what it is.我已经尝试了几种代码变体,但似乎都不起作用,我可能做错了什么,但我无法弄清楚它是什么。

Here is a screenshot of a test with Advanced REST client : ARC screenshot这是使用高级 REST 客户端进行测试的屏幕截图: ARC 屏幕截图

And here is what I mean by "it seems like it's corrupted" : Windows Photo Viewer screenshot这就是我所说的“它似乎已损坏”的意思Windows 照片查看器屏幕截图

Any help is appreciated!任何帮助表示赞赏!

The are two problems which may cause confusion here:这里有两个问题可能会引起混淆:

  1. Media types which are supported by service which define what formats of data can be uploaded correctly to the server.服务支持的媒体类型定义了可以正确上传到服务器的数据格式。

  2. Format of image uploaded which is different than image stored on source computer since none of image media format is supported by yur WebAPI.上传的图像格式与源计算机上存储的图像不同,因为您的 WebAPI 不支持任何图像媒体格式。

In case like your WebAPI client HTTP POST message contains a payload - image, in HTTP header the Content-Type specifies the format of the message body.如果您的 WebAPI 客户端 HTTP POST 消息包含有效载荷 - 图像,则在 HTTP 标头中,Content-Type 指定消息正文的格式。 This tells the Web API how to parse the contents of the message body.这告诉 Web API 如何解析消息正文的内容。 For example, if an HTTP post message to your API contains a PNG image, the POST request might have the following headers:例如,如果发送到 API 的 HTTP 发布消息包含 PNG 图像,则 POST 请求可能具有以下标头:

Content-Length: 95267
Content-Type: image/png

Adding correct media formats attributes to you WebAPI controller class shuld support indicated in them image formats:将正确的媒体格式属性添加到您的 WebAPI 控制器类应该支持以它们的图像格式表示:

 [Route("api/TestUpload")] [Consumes("multipart/form-data")] [Consumes("image/jpg")] [Consumes("image/png")] [Consumes("image/gif")] public class TestUploadController : Controller { }

In the case of any further problems or need to support image formats not available out of box create custom MediaFormatter clas derived from for instance BufferedMediaFormatter and use it in your project.如果有任何进一步的问题或需要支持开箱即用的图像格式,请创建从例如BufferedMediaFormatter派生的自定义MediaFormatter类并在您的项目中使用它。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM