我有一个发布到API的附件的<input type='file' />数组,但是我得到的files数组参数为空,我遗漏了什么?我是否在api上声明了正确的类型(IEnumerable<IFormFileCollection> 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);
};发布于 2019-06-05 01:03:07
多亏了上面的评论(特别感谢@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)https://stackoverflow.com/questions/56425969
复制相似问题