5

I'm trying to use react-admin to send data to my custom API. I want to send files, I can see that there is , I'd like to send that data as multi-part form data. I have come across the base64 encoding help page, as a newcomer to react, it is hard for me to figure out what I need to do to turn it in to multi-part form data.

If someone could walk me through the code that makes it work, that'd be great! I'm here to learn.

Thanks so much in advance.

Akos Veres
  • 63
  • 1
  • 4

1 Answers1

8

I had the same problem, this is my solution:

import { fetchUtils } from "react-admin";
import restServerProvider from 'ra-data-json-server';

const servicesHost = 'http://my-services-host';

const httpClient = (url, options = {}) => {
    if (!options.headers) {
        options.headers = new Headers({ Accept: 'application/json' });
    }
    const token = localStorage.getItem('token');
    options.headers.set('Authorization', `Bearer ${token}`);
    return fetchUtils.fetchJson(url, options);
};

const dataProvider = restServerProvider(servicesHost, httpClient);

const myDataProfider = {
    ...dataProvider,
    create: (resource, params) => {
        if (resource !== 'resource-with-file' || !params.data.theFile) {
            // fallback to the default implementation
            return dataProvider.create(resource, params);
        }

        let formData = new FormData();

        formData.append('paramOne', params.data.paramOne);
        formData.append('paramTwo', params.data.paramTwo);
        formData.append('theFile', params.data.theFile.rawFile);

        return httpClient(`${servicesHost}/${resource}`, {
            method: 'POST',
            body: formData,
        }).then(({ json }) => ({
            data: { ...params.data, id: json.id },
        }));
    }
};

export default myDataProfider;
Mark Girgis
  • 125
  • 1
  • 9
Nico Dante
  • 96
  • 1
  • 2