Reputation: 139
I would like to convert the response of react-native-document-picker to base64 format. As a response I get the Uri of the file but unfortunately no base64.
this is my code:
const openDocumentFile = async () =>{
try {
const results = await DocumentPicker.pickMultiple({
type: [DocumentPicker.types.pdf],
readContent: true
});
for (const res of [results]) {
console.log(res)
};
} catch (err) {
if (DocumentPicker.isCancel(err)) {
} else {
throw err;
}
}
} ```
Upvotes: 7
Views: 9920
Reputation: 1
import DocumentPicker from 'react-native-document-picker';
import RNFetchBlob from 'react-native-blob-util';
const [result, setResult] = React.useState<
| {
name: string;
type: string;
size: number | null;
extension: string;
blob: any;
path: string;
}[]
| undefined
| null
>(null);
const handleDocumentUpload = async () => {
try {
const res = await DocumentPicker.pickSingle();
if (!res) {
throw new Error('File pick cancelled or failed');
}
const {
type: fileType,
uri: fileUri,
name: fileName,
size: fileSize,
} = res;
if (!fileType || !fileUri || !fileName) {
throw new Error('Failed to get file information');
}
const fileExtension = fileType.substr(fileType.indexOf('/') + 1);
let realURI = fileUri;
if (Platform.OS === 'ios') {
realURI = decodeURI(fileUri);
}
const base64Data = await getBase64Data(realURI);
const sanitizedFileName = fileName.replace(/\s/g, '');
const path = '/patients';
const newUploadedFile = [
{
name: sanitizedFileName,
type: fileType,
size: fileSize,
extension: fileExtension,
blob: base64Data,
path: Array.isArray(path) ? path.join() : path,
},
];
setResult(newUploadedFile);
} catch (error) {
console.error('Error picking or processing file:', error);
}
};
const getBase64Data = async (uri: string) => {
try {
const base64Data = await RNFetchBlob.fs.readFile(uri, 'base64');
return base64Data;
} catch (error) {
console.error('Error reading file as base64:', error);
throw new Error('Failed to read file');
}
};
Upvotes: 0
Reputation: 655
You can also use react-native-fs library. It's better to decode the file path/uri.
import RNFS from 'react-native-fs';
...
const base64 = await RNFS.readFile(decodeURIComponent(filePath), 'base64');
...
Upvotes: 1
Reputation: 248
you can use one this libs
react-native-image-base64 or rn-fetch-blob
import RNFetchBlob from 'rn-fetch-blob';
RNFetchBlob.fs
.readFile(filePath, 'base64')
.then((data) => {
setdata(data);
})
.catch((err) => {});
Upvotes: 6