Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'rn-fetch-blob' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
saveImageWithAndroid = async (url: string) => {
// url最后一个反斜线的位置
const lastIndex = url.lastIndexOf('/');
// 通过位置得到图片名称
const imageName = url.substr(lastIndex);
const config = {
fileCache: true,
path: Dirs.DCIMDir + imageName
};
try {
// 下载图片
await FetchBlob.config(config).fetch('GET', url);
await FetchBlob.fs.scanFile([{ path: Dirs.DCIMDir + imageName, mime: '' }]);
alert('保存成功');
} catch (e) {
console.log(e);
alert('保存失败');
}
};
export async function saveDataForTile (tile) {
const viewport = tileToBBOX(quadkeyToTile(tile))
const bbox = [[viewport[2], viewport[3]], [viewport[0], viewport[1]]]
const url = `${mapSlug}/?bbox=${bboxToString(bbox)}`
const path = `${RNFetchBlob.fs.dirs.DocumentDir}/${tile.slice(0, 8)}/${tile}.osm.xml`
const tmpPath = `${path}.tmp`
const rsp = await RNFetchBlob.config({
followRedirect: false,
path: tmpPath
}).fetch('GET', url, {
...await getOAuthHeaders(url)
})
if (rsp.info().status !== 200) {
console.log(`${url} failed with status code ${rsp.info().status}: ${await rsp.text()}`)
throw new Error(`Request to ${url} failed with status code ${rsp.info().status}`)
}
const stat = await RNFetchBlob.fs.stat(rsp.path())
// once we are sure the file is fully downloaded, we move it to its final location
// so that readers never get a half-written file.
try {
await RNFetchBlob.fs.unlink(path)
export function* addImage ({uri, data}) {
// console.log(`ipfs.addImage`)
// console.log(uri)
const file = Platform.OS === 'ios' ? uri.replace('file://', '') : uri
return yield call(addFile, {name: 'file', filename: 'avatar.jpg', type: 'image/jpeg', data: RNFetchBlob.wrap(file)})
}
): Promise {
console.log(
`[Dropbox backup] UPLOADING local file [${localFilePath}] to remote file [${dropboxFilePath}]!`
);
return RNFetchBlob.fetch(
"POST",
DROPBOX.UPLOAD_URL,
{
Authorization: `Bearer ${dropboxAccessToken}`,
"Content-Type": "application/octet-stream",
"Dropbox-API-Arg": JSON.stringify({
path: dropboxFilePath,
mode: "overwrite"
})
},
RNFetchBlob.wrap(localFilePath)
).then((fetchBlobResponse: any) => {
console.log("[Dropbox backup] UPLOAD response!", fetchBlobResponse);
// Ensure we have `data` and a 200 response
if (
fetchBlobResponse.data &&
fetchBlobResponse.respInfo &&
fetchBlobResponse.respInfo.status === 200
) {
console.log("[Dropbox backup] UPLOAD SUCCESS!");
// Record `client_modified` timestamp
const responseData = JSON.parse(fetchBlobResponse.data);
const clientModifiedTimestamp =
responseData[DROPBOX.CLIENT_MODIFIED_TIMESTAMP_KEY];
console.log(
"[Dropbox backup] logging most recent backup timestamp as: " +
clientModifiedTimestamp
private uploadDBToDropbox(
localFilePath: string,
dropboxFilePath: string,
dropboxAccessToken: string
): Promise {
console.log(
`[Dropbox backup] UPLOADING local file [${localFilePath}] to remote file [${dropboxFilePath}]!`
);
return RNFetchBlob.fetch(
"POST",
DROPBOX.UPLOAD_URL,
{
Authorization: `Bearer ${dropboxAccessToken}`,
"Content-Type": "application/octet-stream",
"Dropbox-API-Arg": JSON.stringify({
path: dropboxFilePath,
mode: "overwrite"
})
},
RNFetchBlob.wrap(localFilePath)
).then((fetchBlobResponse: any) => {
console.log("[Dropbox backup] UPLOAD response!", fetchBlobResponse);
// Ensure we have `data` and a 200 response
if (
fetchBlobResponse.data &&
export const fakeUserAvatar = (): Promise => {
// save each connection with their id as the async storage key
return RNFetchBlob.fetch('GET', 'https://loremflickr.com/180/180/all', {})
.then((res) => {
if (res.info().status === 200) {
let b64 = res.base64();
return b64;
} else {
return 'https://loremflickr.com/180/180/all';
}
})
.catch((err) => console.log(err));
};
async function initialize(dispatch) {
shimInit();
// blobTest();
Setting.setConstant('env', __DEV__ ? 'dev' : 'prod');
Setting.setConstant('appId', 'net.cozic.joplin-mobile');
Setting.setConstant('appType', 'mobile');
//Setting.setConstant('resourceDir', () => { return RNFetchBlob.fs.dirs.DocumentDir; });
Setting.setConstant('resourceDir', RNFetchBlob.fs.dirs.DocumentDir);
const logDatabase = new Database(new DatabaseDriverReactNative());
await logDatabase.open({ name: 'log.sqlite' });
await logDatabase.exec(Logger.databaseCreateTableSql());
const mainLogger = new Logger();
mainLogger.addTarget('database', { database: logDatabase, source: 'm' });
mainLogger.setLevel(Logger.LEVEL_INFO);
if (Setting.value('env') == 'dev') {
mainLogger.addTarget('console');
mainLogger.setLevel(Logger.LEVEL_DEBUG);
}
reg.setLogger(mainLogger);
reg.setShowErrorMessageBoxHandler((message) => { alert(message) });
const { map: { mode } } = getState()
// there may be other modes in which we don't want to fetch data
if (zoom >= 16 && mode !== 'bbox') {
// load data
await dispatch(fetchData(visibleBounds))
const tiles = bboxToTiles(visibleBounds)
// load data for all visible tiles into the cache (read by selectors.getVisibleFeatures)
for (const tile of tiles) {
try {
if (!cache.has(tile)) {
// insert a placeholder to avoid doing this multiple times
cache.set(tile, false)
const filename = `${RNFetchBlob.fs.dirs.DocumentDir}/${tile.slice(0, 8)}/${tile}.osm.xml`
if (await RNFetchBlob.fs.exists(filename)) {
const data = await RNFetchBlob.fs.readFile(filename, 'utf8')
const xmlData = XML_PARSER.parseFromString(data, 'text/xml')
const geoJSON = osmtogeojson(filterRelations(xmlData), {
flatProperties: true,
wayRefs: true
})
cache.set(tile, geoJSON)
dispatch({
type: types.NEW_DATA_AVAILABLE
})
} else {
// OSM XML for this tile doesn't exist (yet)
cache.del(tile)
}
export const getCacheFile = async (name, uri) => {
const filename = name || uri.substring(uri.lastIndexOf('/'), uri.indexOf('?') === -1 ? uri.length : uri.indexOf('?'));
const defaultExt = `.${getExtensionFromMime(DEFAULT_MIME_TYPE)}`;
const ext = filename.indexOf('.') === -1 ? defaultExt : filename.substring(filename.lastIndexOf('.'));
let path = `${IMAGES_PATH}/${Math.abs(hashCode(uri))}${ext}`;
try {
const isDir = await RNFetchBlob.fs.isDir(IMAGES_PATH);
if (!isDir) {
await RNFetchBlob.fs.mkdir(IMAGES_PATH);
}
} catch (error) {
// do nothing
}
let exists = await RNFetchBlob.fs.exists(path);
if (!exists) {
const pathWithDiffExt = await RNFetchBlob.fs.existsWithDiffExt(path);
if (pathWithDiffExt) {
exists = true;
path = pathWithDiffExt;
}
}
downLoadBundle(url) {
let name = this.getFileName(url)
let dirs = RNFetchBlob.fs.dirs.DocumentDir
let path = dirs + "/" + name
RNFetchBlob
.config({
// 有文件默认覆盖
overwrite:true,
// 下载的指示器,ios执行
indicator:true,
// 允许自建ssl通信
trusty:true,
// add this option that makes response data to be stored as a file,
// this is much more performant.
fileCache: true,
// 拓展
appendExt: 'jsbundle',
// 路径
path:path
})