如何在react-admin graphql中上传图像

时间:2018-12-23 07:22:25

标签: graphql image-upload react-admin

我在react-admin文档中看到了示例数据提供程序,用于处理图像上传并将其转换为Base64,但是我不能将它用于graphql数据提供程序,有人可以帮助我吗?实际上,我需要一段代码来处理react-admin graphql dataprovider中的图像上传

1 个答案:

答案 0 :(得分:0)

您必须创建另一个客户端,以将图像(或文件)转换为base64,并在其周围包裹graphQL客户端。像这样一个:

upload.js

sg

data.js

vpc_id

App.js

import {CREATE, UPDATE} from "react-admin";

/**
 * Convert a `File` object returned by the upload input into a base 64 string.
 * That's not the most optimized way to store images in production, but it's
 * enough to illustrate the idea of data provider decoration.
 */
const convertFileToBase64 = (file) =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.rawFile);

        reader.onload = () => resolve(reader.result);
        reader.onerror = reject;
    });

export default (dataProvider) => (fetchType, resource, params) => {
    if (resource === "Photo" && (fetchType === CREATE || fetchType === UPDATE)) {
        const {data, ...rest_params} = params;
        return convertFileToBase64(data.data).then((base64) => {
            return dataProvider(fetchType, resource, {
                ...rest_params,
                data: {...data, data: base64},
            });
        });
    }
    return dataProvider(fetchType, resource, params);
};