我是react-admin的新手。我正在使用react-admin上传文件。我已按照本教程下面提到的步骤进行操作。
但是在我提交请求之后...我看到如下的http跟踪。我看到的是Blob链接,而不是Base64图像有效负载。
“图片”:{“ rawFile”:{“预览”:“ blob:http://127.0.0.1:3000/fedcd180-cdc4-44df-b8c9-5c7196788dc6”},“ src”:“ blob:http://127.0.0.1:3000/fedcd180-cdc4-44df-b8c9-5c7196788dc6”,“ title”:“ Android_robot.png “}}
有人可以建议如何获取base64图像有效负载而不是链接。
谢谢。
授予
答案 0 :(得分:1)
检查是否有此处理程序, 您很有可能没有将资源“帖子”的名称更改为您的:
const addUploadCapabilities = requestHandler =>(类型,资源,参数)=> { if(type ==='UPDATE'&& resource ==='posts'){
答案 1 :(得分:0)
创建您的自定义 dataProvider 以将图片转换为 base64
import restServerProvider from 'ra-data-json-server';
const servicesHost = 'http://localhost:8080/api';
const dataProvider = restServerProvider(servicesHost);
const myDataProfider = {
...dataProvider,
create: (resource, params) => {
if (resource !== 'your-route' || !params.data.pictures) {
// fallback to the default implementation
return dataProvider.create(resource, params);
}
const myFile = params.data.pictures;
if ( !myFile.rawFile instanceof File ){
return Promise.reject('Error: Not a file...'); // Didn't test this...
}
return Promise.resolve( convertFileToBase64(myFile) )
.then( (picture64) => ({
src: picture64,
title: `${myFile.title}`
}))
.then( transformedMyFile => dataProvider.create(resource, {
...params,
data: {
...params.data,
myFile: transformedMyFile
}
}));
}
};
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 myDataProfider;
并通过您的服务器 API 获取图像数据
exports.create = (req, res) => {
if(req.body.myFile){
var file = req.body.myFile;
var fs = require('fs');
var data = file.src.replace(/^data:image\/\w+;base64,/, "");
var buf = Buffer.from(data, 'base64');
fs.writeFile(`upload/${file.title}`, buf, err => {
if (err) throw err;
console.log('Saved!');
});
}};