【问题标题】:React Fetch sending binary file to .Net Core WebAPI endpointReact Fetch 将二进制文件发送到 .Net Core WebAPI 端点
【发布时间】:2020-05-24 08:37:10
【问题描述】:

我正在尝试将带有一些参数(文件名、相关 ID 等)的二进制文件发送到我的 .Net Core 3 WebAPI 端点。

我的端点如下所示:

[HttpPost, Route("/api/attachment")]
[RequestFormLimits(MultipartBodyLengthLimit = long.MaxValue)]
public async Task<IActionResult> Create([FromForm] AttachmentCreateRequest request)
{

我试图返回并转换为我的 POCO 的模型是:

 public class AttachmentCreateRequest
    {
        public string Description { get; set; }
        public Guid TransactionId { get; set; }
        public IFormFile File { get; set; }
    }

当我发送请求时,Chrome 工具会指示正在发送:

------WebKitFormBoundaryXrahZqoiAk4lYBgv Content-Disposition: form-data;名称=“文件”; filename="eBay_订单详情.pdf" 内容类型:application/pdf

------WebKitFormBoundaryXrahZqoiAk4lYBgv Content-Disposition: form-data; name="transactionId"

762505fe-81bd-4b07-9456-cf7f0bb70efb ------WebKitFormBoundaryXrahZqoiAk4lYBgv Content-Disposition: form-data;名称="描述"

测试 ------WebKitFormBoundaryXrahZqoiAk4lYBgv--

我尝试发送的字段是名为“file”的文件、在上面的数据中似乎可见的 transactionId,以及我将其设置为“test”的名为“description”的字段。

但是方法上的断点,显示为null:

为什么我的文件参数会为空?

关于我的应用程序的详细信息: 我使用通用的 Fetch 方法进行所有调用。在我打的电话中,'isBinary' 是真的。

const fetchData = ({ method = 'GET', URL, data = {}, isBinary = false}) => {
  // Force the content type.
  console.log("FetchData got request:", data)
  const contentType = isBinary ? undefined : 'application/json'
  const header = {
    'Content-Type': contentType,
    Accept: contentType,
  };
  console.log("content type will be", contentType)

  // If we have a bearer token (User seems to be signed in), add it to the header.
  const userIsAuthenticated = Auth.isAuthenticated();
  if (userIsAuthenticated) {
    header.Authorization = `Bearer ${Auth.token()}`;
  }

  // Create the config that will be used for the fetch.
  let config = {
    method,
    headers: header,
  };

  // If this is anything but a GET, set the body to hold the data we're posting.
  if (method !== 'GET' && method !== 'DELETE') {
    if(isBinary)
    {
      console.log("IsBinary.. on't stringify")
      config = Object.assign({}, config, { body: data });
    }
    else
    {
        const stringified = JSON.stringify(data);
        console.log("Body is: ", stringified)

        config = Object.assign({}, config, { body: stringified });
    }
  }

  console.log("Fetch: ", config)
  // Use the browser api, fetch, to make the call.

  return fetch(URL, config)
    .then((raw) => {
      return raw;
    })
    .then((response) => {
      return response;
    })
    .catch((e) => {
      console.timeEnd(`fetchExecutionTime ${URL}`)
      console.log(`An error has occured while calling the API. ${e}`);
    });
};

“数据”字段已定义:

let data = new FormData() 
    data.append('file', this.state.selectedFile)
    data.append('transactionId', this.state.transaction.id)
    data.append('description', 'test')
    console.log("Data now", data)

.. 其中 'selectedFile' 来自选择文件的表单控件。我“附加”了我的 POCO 对象所期望的三个属性。

【问题讨论】:

    标签: c# asp.net-web-api


    【解决方案1】:

    我认为问题归咎于表单标签配置。

    它似乎正确地考虑了从视图接收到的信息和类型,但视图并没有正确发送所有数据。

    你能分享一下sketch relativa form标签吗?

    【讨论】:

    • 对不起,达里奥。我不太确定这意味着什么。
    • 对不起,我会尽量说清楚。您从哪里调用 Create 操作?我认为它是由您使用的表格设置的。我想这是因为action参数中指示了“FromForm”,我的推论是否正确?当动作参数没有被起始表单正确赋值时,在某些情况下它不会给出错误,而只是不传递信息。
    • 好的,这有帮助吗?我已经添加了我的客户端调用代码。
    猜你喜欢
    • 2017-04-27
    • 1970-01-01
    • 2020-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 2010-09-30
    • 2020-10-08
    相关资源
    最近更新 更多