首页 > 解决方案 > 在 Net Core Controller 中接收 IFileForm 并转发到另一个(独立)API

问题描述

我有一个 Vue.JS 应用程序,我在其中将图像上传到 NetCore 控制器。

我在以下控制器中收到 IFileForm:

[HttpPost("UpdateContactPhoto")]
public async Task<string> UpdateContactPhoto(IFormFile file){ //Forward the original IFileForm to another NetCore API.    }

此时一切正常。IFileForm 完美呈现。

我的问题是我需要将此 IFileForm 转发到另一个 API(独立于此),其输入是带有 HttpClient PutAsync 的 IFileForm,但不起作用。

有人能帮我吗?

感谢帮助。

标签: apiasp.net-core.net-coreuploadasp.net-core-mvc

解决方案


你可以使用这个例子。请注意,参数名称与添加到的项目相同form-data

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:57985");

            byte[] data;
            using (var br = new BinaryReader(file.OpenReadStream()))
            {
                data = br.ReadBytes((int) file.OpenReadStream().Length);
            }

            ByteArrayContent bytes = new ByteArrayContent(data);
            MultipartFormDataContent multiContent = new MultipartFormDataContent();

            multiContent.Add(bytes, "file", file.FileName);

            var result = client.PutAsync("api/v1/FileManager", multiContent).Result;

            if (result.StatusCode == HttpStatusCode.OK)
            {
                //do some things
            }
        }

您还可以使用此代码从以下位置获取文件HttpContext

    IFormFile file = HttpContext.Request.Form.Files[0];

推荐阅读