I am using RNFetchBlob to share image as base64 format. But the image is downloading in my local folder. I want to delete it. By my research knowledge i want to unlink the image path. I don't know how to do that. Here is my code
_downloadImageAndShare(url ,title, message) {
const { fs } = RNFetchBlob.fs;
const self = this;
RNFetchBlob.config({ fileCache: true })
.fetch('GET', url)
.then(resp => resp.readFile('base64')
.then(base64 => ({ resp, base64 })))
.then(obj => {
const headers = obj.resp.respInfo.headers;
const type = headers['Content-Type'];
const dataUrl = 'data:' + type + ';base64,' + obj.base64;
return { url: dataUrl, title, message };
})
.then(options => Share.open(options)).catch(err => {err &&
console.log(err); })
}
how to use this code inside this method
RNFetchBlob.fs.unlink(path)
.then(() => { ... })
.catch((err) => { ... })
and how to specify the unlink(path) ??
thanks in advance.
You can specify file location with config with path param.
const filePath = RNFetchBlob.fs.dirs.DocumentDir + '/myFile';
RNFetchBlob.config({ fileCache: true, path : filePath })
.fetch('GET', url)
.then(resp => resp.readFile('base64')
.then(base64 => ({ resp, base64 })))
.then(obj => {
const headers = obj.resp.respInfo.headers;
const type = headers['Content-Type'];
const dataUrl = 'data:' + type + ';base64,' + obj.base64;
return { url: dataUrl, title, message };
})
.then(options => Share.open(options)).catch(err => {err &&
console.log(err); })
}
Then you can call unlink like this
RNFetchBlob.fs.unlink(filePath)
.then(() => { ... })
.catch((err) => { ... })
Related
I am replacing axios to rn-fetch-blob in my react-native project. In the request I ping my server with credentials and I expect a response.
The old request with axios is as follows and works perfectly:
export const postWorkspace =
(newWorkspace: Workspace): AppThunk =>
async (dispatch) => {
console.log('addWorkspace Start');
dispatch(setIsLoading(true));
let configOption = {
headers: {
'Access-Control-Allow-Origin': '*',
'X-AUTH-USER': newWorkspace.credentials.email,
'X-AUTH-TOKEN': newWorkspace.credentials.password,
},
};
await axios
.get(`${newWorkspace.url}/api/ping`, configOption)
.then(async (resp) => {
console.log('addWorkspace resp', resp);
try {
await storeWorkspaceToStorage(newWorkspace);
} catch (e) {
console.error(e);
}
})
.catch((err) => {
console.log('addWorkspace err', JSON.stringify(err));
return Promise.reject(err);
})
.finally(() => dispatch(setIsLoading(false)));
};
This is how I transformed the code with rn-fetch-blob:
export const postWorkspace=
(newWorkspace: Workspace): AppThunk =>
async (dispatch) => {
console.log('addWorkspace Start');
dispatch(setIsLoading(true));
let configOption = {
'Access-Control-Allow-Origin': '*',
'X-AUTH-USER': newWorkspace.credentials.email,
'X-AUTH-TOKEN': newWorkspace.credentials.password,
};
await RNFetchBlob
.fetch('GET', '${newWorkspace.url}/api/ping', configOption)
.then( async(resp) => {
console.log('addWorkspace resp', resp);
try {
await storeWorkspaceToStorage(newWorkspace);
} catch (e) {
console.error(e);
}
})
.catch((err) => {
//console.log(err.info().status);
console.log('addWorkspace err', JSON.stringify(err));
return Promise.reject(err);
})
.finally(() => dispatch(setIsLoading(false)));
};
The new request with rn-fetch-blob returns this error:
response error "line":126349,"column":34,"sourceURL":"http://localhost:8081/index.bundle?platform=android&dev=true&minify=false"
When I opend the file "http://localhost:8081/index.bundle?platform=android&dev=true&minify=false" around line 1262349 the code looks like this, I can't understand what went wrong:
var req = RNFetchBlob[nativeMethodName];
req(options, taskId, method, url, headers || {}, body, function (err, rawType, data) {
subscription.remove();
subscriptionUpload.remove();
stateEvent.remove();
partEvent.remove();
delete promise['progress'];
delete promise['uploadProgress'];
delete promise['stateChange'];
delete promise['part'];
delete promise['cancel'];
promise.cancel = function () {};
//line 126349
if (err) reject(new Error(err, respInfo));else {
if (options.path || options.fileCache || options.addAndroidDownloads || options.key || options.auto && respInfo.respType === 'blob') {
if (options.session) session(options.session).add(data);
}
respInfo.rnfbEncode = rawType;
resolve(new FetchBlobResponse(taskId, respInfo, data));
}
});
});
I am doing this since rn-fetch-blob is basically one of the few libraries that allows react-native to ping a server with no SSL certification.
Thank you
I'm having trouble saving a .DOC file using expo-file-system.
I'm getting the following feedback:
[Unhandled promise rejection: Error: Invalid argument "localUri". It
must be a string!]
This is my current code:
useEffect(() => {
const saveFile = async () => {
const { granted } = await Notifications
.requestPermissionsAsync()
.then((response) => response)
.catch((error) => error);
console.log(granted);
if (granted) {
data.map(async (index) => {
const date = new Date(index.synchronization)
const formattedDate = date.toISOString().split('T')[0];
const fileUri = `${FileSystem.documentDirectory}${formattedDate}.doc`;
console.log(fileUri)
await FileSystem.writeAsStringAsync(
fileUri,
"Hello World, i'am saving this file :)",
{
encoding: FileSystem.EncodingType.UTF8
});
const asset = await MediaLibrary.createAssetAsync(`${fileUri}`);
await MediaLibrary.createAssetAsync(asset);
console.log(asset);
});
}
}
saveFile();
}, [data]);
The error is probably occurring on this line:
const asset = await MediaLibrary.createAssetAsync(`${fileUri}`);
await MediaLibrary.createAssetAsync(asset);
Okay, I did!
It's a boring prank these promises
const { uri } = await MediaLibrary
.createAssetAsync(`${fileUri}`)
.then((response) => response)
.catch((error) => error);;
await MediaLibrary.createAssetAsync(uri);
Necessita do uso de then and catch
This is a homework type question, please help as I'm new on react-native.
In react-native, I'm using react-native-document-picker, from the code in readme:
selectFiles = () => {
try {
DocumentPicker.pickMultiple({
type: [DocumentPicker.types.allFiles],
}).then((results) => {
console.log(result[0].uri);
}
});
} catch (err) { }
};
It provides me with an URI, how can convert that into path and read data of that file ?
Here is my solution :
var RNFS = require('react-native-fs');
...
RNFS.readFile(results[0].uri)
.then((file) => {
that.setState({code: file});
})
.catch((error) => console.log('err: ' + error));
I am new to react-admin. I am using react-admin to upload the file. I have following the step mentioned below in tutorial.
But after I submit the request...I see http trace as follow. I see blob link instead of Base64 image payload.
{
"pictures": {
"rawFile": {
"preview": "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"
}
}
Can someone please advice how to get base64 image payload instead of link?
Check to see if you have this handler, most likely you did not change the name of the resource posts to your:
const addUploadCapabilities = requestHandler => (type, resource, params) => {
if (type === 'UPDATE' && resource === 'posts') {
Create your custom dataProvider to convert picture to 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;
And get image data at your Server 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!');
});
}};
How do we implement caching in react-native-video? Basically, when a video is currently streaming from a network resource, how do we save the video somewhere, and then retrieve it when the same resource is access. What is the best approach for this?
The best approach that i would refer you is using react-native-fetch-blob, you can implement it like this:
const RNFetchBlob = require('react-native-fetch-blob').default;
const {
fs
} = RNFetchBlob;
const baseCacheDir = fs.dirs.CacheDir + '/videocache';
//call the downloadVideo function
downloadVideo('http://....',baseCacheDir)
//Function to download a file..
const activeDownloads = {};
function downloadVideo(fromUrl, toFile) {
// use toFile as the key
activeDownloads[toFile] = new Promise((resolve, reject) => {
RNFetchBlob
.config({path: toFile})
.fetch('GET', fromUrl)
.then(res => {
if (Math.floor(res.respInfo.status / 100) !== 2) {
throw new Error('Failed to successfully download video');
}
resolve(toFile);
})
.catch(err => {
return deleteFile(toFile)
.then(() => reject(err));
})
.finally(() => {
// cleanup
delete activeDownloads[toFile];
});
});
return activeDownloads[toFile];
}
//To delete a file..
function deleteFile(filePath) {
return fs.stat(filePath)
.then(res => res && res.type === 'file')
.then(exists => exists && fs.unlink(filePath)) //if file exist
.catch((err) => {
// swallow error to always resolve
});
}
Cheers:)