简体   繁体   中英

Post `<input type='file' />` array

I have an <input type='file' /> array of attachments that I post to an API, but I'm getting the files array param empty, what am I missing? Am I declaring the correct type ( IEnumerable<IFormFileCollection> files ) on the api?

The query string parameters are passing fine.

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' },
    });

And the 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);
};

Thanks to the above comments (especially thanks to @Liam for the excellent example he referred me to) I was able to figure it out:

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' },
});

I changed the apiPost method to get a header param:

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);
};

And finally the api controller:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM