首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Post `<input type='file‘/>`数组

Post `<input type='file‘/>`数组
EN

Stack Overflow用户
提问于 2019-06-03 18:59:50
回答 1查看 284关注 0票数 1

我有一个发布到API的附件的<input type='file' />数组,但是我得到的files数组参数为空,我遗漏了什么?我是否在api上声明了正确的类型(IEnumerable<IFormFileCollection> files)?

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

代码语言:javascript
复制
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:

代码语言:javascript
复制
[HttpPost]
[Route("attachments")]
public async Task<string> addAttachments(string request, int ticketId, [FromBody]IEnumerable<IFormFileCollection> files)
{...}

apiPost

代码语言:javascript
复制
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);
};
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-05 01:03:07

多亏了上面的评论(特别感谢@Liam给我举了一个很好的例子),我才能弄明白:

代码语言:javascript
复制
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参数:

代码语言:javascript
复制
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控制器:

代码语言:javascript
复制
[HttpPost]
[Route("attachments")]
public async Task<string> addAttachments(string request, int ticketId, IEnumerable<IFormFile> files)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56425969

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档