我有一个<input type='file' />
附件数组,我将它们发布到API,但是我却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);
};
答案 0 :(得分:0)
由于上述评论(特别感谢@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)