【问题标题】:How to receive MultipartFormDataContent in API?如何在 API 中接收 MultipartFormDataContent?
【发布时间】:2021-08-22 06:54:42
【问题描述】:

网络核心应用程序。我有一个 REST API,它会将文件发送到另一个 API。

以下是第一个 API 内部将文件发送到第二个 API 的逻辑。

using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await _tokenService.GetToken());
                    MultipartFormDataContent multipartFormData = new MultipartFormDataContent();
                    string contentJson = JsonConvert.SerializeObject(request);
                    HttpContent data = new StringContent(contentJson, Encoding.UTF8, "application/json");
                    multipartFormData.Add(data, "data");
                    foreach (var file in fileList)
                    {
                        if (file.Length <= 0)
                            continue;
                        var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                        multipartFormData.Add(new StreamContent(file.OpenReadStream())
                        {
                            Headers =
                            {
                        ContentLength = file.Length,
                        ContentType = new MediaTypeHeaderValue(file.ContentType)
                            }
                        }, "File", fileName);
                    }
                    try
                    {
                        var response = await client.PostAsync("https://localhost:44370/apisendfile", multipartFormData);
                    }
                    catch (Exception ex)
                    {
                    }
                }

我有如下第二个 API

 public async Task<ActionResult> SendMail([FromBody] MultipartFormDataContent formDataContent)
        {
        }

当我在我的第一个 API 中调试时收到错误

不支持的媒体类型

我一直在尝试解决这个问题,但未能成功。有人可以帮我确定这个问题。任何帮助,将不胜感激。谢谢

【问题讨论】:

  • 分享您的完整控制器代码。
  • 嗨,Md Farid Uddin。我在上面分享了第一个 api 代码,在第二个 api 中保存文件,但我的问题是第一次尝试调用第二个 api 并且由于媒体类型不受支持而失败。
  • 我不确定您在Posting Multipart 或接收Multipart 数据时遇到问题?您可以阅读我们的offical document here
  • 嗨 HD Farid Uddin,我在接收 multipat 时遇到问题
  • 好的,你可以试试我提供的解决方案。如果您对此有进一步的担忧,请随时分享。

标签: c# asp.net-core file-upload httpclient iformfile


【解决方案1】:

嗯,你可以试试下面的方法,

Web API 控制器:

        [HttpPost]
        public string UploadMultipartFile()
        {
            var file = HttpContext.Current.Request.Files.Count > 0 ?
                HttpContext.Current.Request.Files[0] : null;

            if (file != null && file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);

                var path = Path.Combine(
                    HttpContext.Current.Server.MapPath("~/MrPerfectMaltipartFolder"),
                    fileName
                );

                file.SaveAs(path);
            }

            return file != null ? "/MrPerfectMaltipartFolder/" + file.FileName : null;
        }

文件夹位置:

在 Post Man 上测试:

打开文件夹位置:

文件上传:

对于 N 类型的分段数据上传:

    [HttpPost]
    public object UploadMultipartFileList()
    {
        var uploadedFilesName = new List<string>();
        if (HttpContext.Current.Request.Files.Count > 0)
        {
            int count = 0;
           
            foreach (var item in HttpContext.Current.Request.Files)
            {


                var getFile = HttpContext.Current.Request.Files[count];
                if (getFile != null)
                {
                    var fileName = Path.GetFileName(getFile.FileName);

                    var path = Path.Combine(
                        HttpContext.Current.Server.MapPath("~/MrPerfectMaltipartFolder"),
                        fileName
                    );

                    getFile.SaveAs(path);
                }
                count++;
                string file = "/MrPerfectMaltipartFolder/" + getFile.FileName;
                uploadedFilesName.Add(file);
            }
        }




        return uploadedFilesName;
    }

输出:

数据和文件示例:

        [HttpPost]
        public object UploadMultipartFileList()
        {
            HttpRequest multipartRquest = HttpContext.Current.Request;
          
           //General Data Part
            string engineerName = multipartRquest.Form["EngineerName"];
            string engineerEmail = multipartRquest.Form["EngineerEmail"];

            //File Upload Part
            var FilesName = new List<string>();
            if (HttpContext.Current.Request.Files.Count > 0)
            {
                int count = 0;
               
                foreach (var item in HttpContext.Current.Request.Files)
                {


                    var getFile = HttpContext.Current.Request.Files[count];
                    if (getFile != null)
                    {
                        var fileName = Path.GetFileName(getFile.FileName);

                        var path = Path.Combine(
                            HttpContext.Current.Server.MapPath("~/MrPerfectMaltipartFolder"),
                            fileName
                        );

                        getFile.SaveAs(path);
                    }
                    count++;
                    string file = "/MrPerfectMaltipartFolder/" + getFile.FileName;
                    FilesName.Add(file);
                }
            }




            return FilesName;
        }

请求格式:

输出:

希望它能解决您的问题。如果您仍然遇到任何问题,请随时分享。

【讨论】:

  • 感谢您的详细解答。 HttpContext.Current.Request.Files.Count 将读取文件,但我也会发送我请求的其他数据(如模型)。那么我怎样才能得到所有这些数据呢?
  • 不用担心,请查看更新后的答案,现在,所有问题都应该立即解决,这样对您和贡献者都会有好处。祝你有美好的一天。
  • 很高兴在这方面为您提供帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-27
  • 2023-02-08
  • 1970-01-01
  • 2019-11-29
  • 1970-01-01
  • 2022-08-16
  • 2013-12-17
相关资源
最近更新 更多