无法在ASP.NET Core Web API中上传图片文件-POST方法

问题描述

我正在尝试上传单个图像文件。示例代码如下:

        /// <summary>
        /// Uploads a single image document 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("{id}/scan-doc-image")]
        //[RequestFormLimits(ValueLengthLimit = int.MaxValue,MultipartBodyLengthLimit = int.MaxValue)]
        public async Task<ActionResult> UploadImage(int id,IFormFile file)
        {
            // more validation goes here.
            if (file == null)
            {
                return BadRequest();
            }

            // save image if any
            if (file.Length > 0)
            {
                var uploads = Path.Combine(_envirnment.WebRootPath,"uploads");

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

            return Ok();
        }

这是我注意到的:

  1. 对此API的调用会自动停止该服务。我尝试了很多次,但总是会失败。当我进行其他API调用时,它没有停止服务。仅供参考

  2. 我也尝试过从POSTMAN拨打电话。这次,它没有关闭服务,但是我不断收到错误消息:Failed to read the request form. Missing content-type boundary. 请注意,我将Content-Type指定为multipart/form-data。当我指定边界小于最大的数字时,它仍然会出错。即使我取消注释了上面看到的RequestFormLimit属性,它也无济于事。

那么我在这里想念的是什么?我需要它来上传单个图像文件。

解决方法

我也尝试过从POSTMAN拨打电话。这次没关 服务,但我不断收到错误:无法读取请求 形成。缺少内容类型边界。请注意,我正在指定 Content-Type为multipart / form-data。当我指定边界 数量少于最大数量,仍然会出错。即使我没有评论 您在上面看到的RequestFormLimit属性也没有帮助。

enter image description here 无需手动添加Content-Type标头。您将覆盖 Postman 设置的值。只需在POST请求中选择form-data,然后发送您的请求以查看其是否有效。发布header时无需设置form-data。只需删除 Content-Type上传,如下所示。

enter image description here





注意可能导致错误的路径

如果您正在使用Web API项目,则_envirnment.WebRootPath中将为null。 Web API项目中没有wwww目录。

enter image description here

解决方案

更改WebRootPath

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

ContentRootPath

        var uploads = Path.Combine(_envirnment.ContentRootPath,"uploads");

测试

enter image description here

控制器代码

如果指定的文件夹“上载”不存在,请首先创建它,然后将文件保存到该文件夹​​中。如果该文件夹已经存在,只需将文件保存在其中。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace WebAPIDemos.Controllers
{

    [ApiController]
    [Route("[controller]")]
    public class FileController : ControllerBase
    {
        private readonly IWebHostEnvironment _envirnment;

        public FileController(IWebHostEnvironment appEnvironment)
        {
            _envirnment = appEnvironment;
        }

        [HttpPost]
        [Route("{id}/scan-doc-image")]
        //[RequestFormLimits(ValueLengthLimit = int.MaxValue,MultipartBodyLengthLimit = int.MaxValue)]
        public async Task<ActionResult> UploadImage(int id,IFormFile file)
        {
            // more validation goes here.
            if (file == null)
            {
                return BadRequest();
            }

            // save image if any
            if (file.Length > 0)
            {
                //var uploads = Path.Combine(_envirnment.WebRootPath,"uploads");
                var uploads = Path.Combine(_envirnment.ContentRootPath,"uploads");

                var destinationDirectory = new DirectoryInfo(uploads);

                if (!destinationDirectory.Exists)
                    destinationDirectory.Create();


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

            return Ok();
        }
    }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...