【问题标题】:Post `<input type='file' />` array发布 `<input type='file' />` 数组
【发布时间】:2019-06-03 10:59:50
【问题描述】:

我有一个 &lt;input type='file' /&gt; 附件数组,我将它们发布到 API,但我将 files 数组参数设置为空,我缺少什么?我是否在 api 上声明了正确的类型(IEnumerable&lt;IFormFileCollection&gt; files)?

查询字符串参数传递正常。

const  attachments  = Array.from(fileList);

const files = attachments;

const result = await apiPost(`api/attachments/addAttachments?request=${request}&&ticketId=${ticketId}`, files, {
      headers: { 'Content-Type': 'multipart/form-data' },
    });

还有 API:

[HttpPost]
[Route("attachments")]
public async Task<string> addAttachments(string request, int ticketId, [FromBody]IEnumerable<IFormFileCollection> files)
{...}

apiPost:

import { AdalConfig, adalFetch } from 'react-adal';

export const apiFetch: <T>(url: string, options?: object) => Promise<T> = (
  url: string,
  options: object,
) => adalFetch(authContext, adalConfig.endpoints.api, axios, url, options);

export const apiPost = async <T>(url: string, data: object): Promise<T> => {
  const options = {
    method: 'post',
    data,
    config: {
      headers: {
        'Content-Type': 'application/json',
      },
    },
  };
  return apiFetch(url, options);
};

【问题讨论】:

  • 这是有角度的吗?
  • @Liam 不,不是
  • apiPost 是什么?
  • apiPost 接受两个参数,而您传递files 的唯一位置是作为第三个参数...?
  • 您的内容类型错误,需要使用multipart/form-data上传文件。您不能使用application/json 上传文件,它不支持文件上传。 This question 似乎涵盖了你需要的一切

标签: javascript c# reactjs


【解决方案1】:

感谢上面的 cmets(特别感谢 @Liam 提供了他提到的优秀示例)我能够弄清楚:

const files = { ...attachments };

const data = new FormData();
// Append files to form data
for (let i = 0; i < attachments.length; i++) {
  data.append('files', files[i], files[i].name);
}

const { result } = apiPost(`api/attachments/addAttachments?request=${request}&ticketId=${ticketId}`, data, {
  headers: { 'Content-Type': 'multipart/form-data' },
});

我更改了apiPost 方法以获得header 参数:

export const apiPost = async <T>(url: string, data: object, headers: object): Promise<T> => {
  const options = {
    method: 'post',
    data,
    config: {
      headers: headers || {
        'Content-Type': 'application/json',
      },
    },
  };
  console.log(data);
  console.log(options);
  return apiFetch(url, options);
};

最后是 api 控制器:

[HttpPost]
[Route("attachments")]
public async Task<string> addAttachments(string request, int ticketId, IEnumerable<IFormFile> files)

【讨论】:

    猜你喜欢
    • 2011-12-31
    • 2017-12-04
    • 1970-01-01
    • 2017-11-26
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    • 2010-09-23
    相关资源
    最近更新 更多