Downloading remote image to local device is not listed in the Photo Library - react-native

I am developing a React Native application. Now, I am trying to download a remote image into the local device.
This is my code:
downloadFile = () => {
var date = new Date();
var url = 'https://static.standard.co.uk/s3fs-public/thumbnails/image/2016/05/22/11/davidbeckham.jpg?w968';
var ext = this.extention(url);
ext = "." + ext[0];
const { config, fs } = RNFetchBlob
let PictureDir = fs.dirs.PictureDir
let options = {
fileCache: true,
addAndroidDownloads : {
useDownloadManager : true,
notification : true,
path: PictureDir + "/image_"+Math.floor(date.getTime() + date.getSeconds() / 2)+ext,
description : 'Image'
}
}
config(options).fetch('GET', url).then((res) => {
Alert.alert("Success Downloaded");
});
}
extention = (filename) => {
return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;
}
I am following this tutorial, https://medium.com/#derrybernicahyady/simple-download-file-react-native-2a4db7d51597?fbclid=IwAR1XR75fivHPtE8AfpXKUuFdaLIOehii4ahI4u0lMVgu7ee62yVmnqDnd04. When I run my code, it says the download was successful. But when I checked my photo library, the image is not there. What is wrong with my code?

Use CameraRoll.saveToCameraRoll method for this instead.

Related

How to download files through development vscode extension on code-server?

I wrote a vscode extension. Now you want to download a file in the vscode working directory by developing extensions. But no files were obtained through vscode vscode.Uri.file.
const downloadPanel = vscode.window.createWebviewPanel(
"view",
"下载",
vscode.ViewColumn.Two,
{
enableScripts: true,
retainContextWhenHidden: true,
}
)
if (vscode.workspace.workspaceFolders === undefined) {
throw new Error("not found!");
}
const filePath = vscode.workspace.workspaceFolders[0].uri.fsPath;
let downloadContent = vscode.commands.registerCommand('download.click', () => {
console.log("filePath = " + filePath);
const onDiskPath = vscode.Uri.file(
path.join(context.extensionPath, "resources","blockchain.svg")
);
// And get the special URI to use with the webview
const catGifSrc = panel.webview.asWebviewUri(onDiskPath) + "";
getWebviewContent(catGifSrc);
function getWebviewContent(_src: string) {
return '<html><head><script></script></script></head><body><div>download</div></body></html>';
}
When clicking the link, the file is not found! Currently, only nginx proxy can be used for full path downloading. Is there any other plan or solution?

React Native : Unable to locate audio file after download

I'm using react-native-simple-download-manager to download audio files into the app's download folder :
headers = {
Authorization: "Téléchargement"
};
config = {
downloadTitle: `${audio.Title}`,
downloadDescription: "Téléchargement",
saveAsName: audio.Title +'.mp3',
allowedInRoaming: true,
allowedInMetered: true,
showInDownloads: true,
external: false, //when false basically means use the default Download path (version ^1.3)
};
downloadManager
.download((url = audio.FileUrl), (headers = headers), (config = config))
.then(response => {
saveData(audio);
})
.catch(err => {
if(index > -1) {
global.downloadingSongId.splice(index,1);
}
});
I can find the downloaded audio files on the phone, but the player can't read the audio given by the
following path : dirs.DocumentDir + '/Download/' + audio.Title + '.mp3'
And when I use RNFetchBlob to check if the path exists it always return false :
let path = dirs.DocumentDir + '/' + audio.Title + '.mp3';
RNFetchBlob.fs.exists(path);
I really appreciate if anyone could help!

Ionic 4 Image upload using Angular HTTP

I use Ionic 4 and Angular 7 with PHP as Back-end.
I am trying to upload files (images/videos/PDFs/audio).
Is there a general way to send it.
I tried to send image using camera plugin it returns the URI and it works on the app using img tag.
But I can't get the file it self to send it using formData
openCamera() {
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
};
this.camera.getPicture(options).then((imageData) => {
this.imageData = imageData;
this.image = (<any>window).Ionic.WebView.convertFileSrc(imageData);
// this.image works fine in img tag
this.sendMsg(this.image);
}, (err) => {
// Handle error
alert('error ' + JSON.stringify(err));
});
}
sendMsg(file?) {
const data = new FormData();
data.set('group_id', this.groupId);
data.set('text', this.msg);
if (file) {
data.set('file', this.image);
data.set('text', '');
}
this.messeges.push(data);
this._messengerService.postMsg(data).subscribe(
res => {
console.log('res ', res);
if (res.success === true) {
console.log('data added ', res);
}
}
);
}
I want the use the URI to get the actual file
Ionic Native plugin will return only base64. As per your question, you need to convert formdata. so, You need to convert base64 to formdata externally.
dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], { type: mimeString });
}
and
profileUpdate(options) {
this.camera.getPicture(options).then((imageData) => {
let base64Image = 'data:image/jpg;base64,' + imageData;
let data = this.dataURItoBlob(base64Image);
let formData = new FormData();
formData.append('profile', data, "filename.jpg");
//here you pass the formdata to to your API
})

How to continue download multiple files (AWS server images) in background in react-native iOS

I created an app where user can download multiple images on one click using react-native-fs which is working perfectly in Android. But in iOS when app is inactive then download stopped and user have to start download again.
async.eachSeries(DownloadData, async function (tourData, finish) {
console.log("# resumable : 655612", tourData);
var fileExtension = '';
var fileURL = tourData.path;
var fileExtension = "/" + tourData.name + "Image" + p + ".png
p = p + 1;
const downloadDest = RNFS.DocumentDirectoryPath + fileExtension;
let dirs = RNFetchBlob.fs.dirs;
var v = dirs.DocumentDir;
var jobId = -1;
const ret = RNFS.downloadFile({
fromUrl: encodeURI(fileURL),
toFile: downloadDest,
connectionTimeout: 1000 * 10,
readTimeout: 1000 * 10,
background: true,
discretionary: true,
progressDivider: 1,
resumable: (res) => {
console.log("# resumable", res);
},
begin: (res) => {
console.log(res)
},
progress: (data) => {
console.log(data)
},
});
jobId = ret.jobId;
RNFS.isResumable(jobId).then(true);
if (await RNFS.isResumable(jobId)) {
console.log("# resumable : # resumable : # resumable :",jobId);
RNFS.resumeDownload(jobId)
}
ret.promise.then((res) => {
finish();
}).catch(err => {
finish();
})
},function (err) {
if (!err) {
callback(true)
} else {
callback(false)
}
}));
Running download in background in IOS require few extra settings check this section https://github.com/itinance/react-native-fs#background-downloads-tutorial-ios
they also mentioned that IOS will give you 30 sec after handleEventsForBackgroundURLSession
BE AWARE! iOS will give about 30 sec. to run your code after handleEventsForBackgroundURLSession is called and until completionHandler is triggered so don't do anything that might take a long time (like unzipping), you will be able to do it after the user re-launces the app, otherwide iOS will terminate your app.
I hope this helps

How to open a local pdf file using OpenURL in Titanium Appceleartor?

In Titanium Appcelerator, i tried to open a PDF file from local directory using OpenURL() method. It's not working properly. i tried on Android device.
My Code;
var myURL = "file:///storage/emulated/0/Android/data/com.test.testapp/cache/_tmp/sample.pdf";
Ti.Platform.openURL(myURL);
Try something like this:
try {
var f = Ti.Filesystem.getFile('your.pdf');
Ti.Android.currentActivity.startActivity(Ti.Android.createIntent({
action: Ti.Android.ACTION_VIEW,
type: 'application/pdf',
data: f.getNativePath()
}));
}
catch (err) {
var alertDialog = Titanium.UI.createAlertDialog({
title: 'No PDF Viewer',
message: 'We tried to open a PDF but failed. Do you want to search the marketplace for a PDF viewer?',
buttonNames: ['Yes','No'],
cancel: 1
});
alertDialog.show();
alertDialog.addEventListener('click', function(evt) {
if (evt.index == 0) {
Ti.Platform.openURL('http://search?q=pdf');
}
});
}
To open a remote PDF natively, you have to download it. Here is a solution which provides the user with options to preview or download the PDF.
var url = "http://www.polyu.edu.hk/iaee/files/pdf-sample.pdf";
var opts = {
cancel: 2,
options: ['Preview', 'Download', 'Cancel'],
selectedIndex: 2,
destructive: 0,
title: 'Open PDF'
};
var dialog = Ti.UI.createOptionDialog(opts);
dialog.addEventListener('click', function(e) {
if (e.index == 0) {
url = "https://docs.google.com/viewer?embedded=true&url=" + url;
var win = Ti.UI.createWindow();
var webView = Ti.UI.createWebView({url:url});
win.add(webView);
win.open();
} else if (e.index == 1) {
var filepath = url.split('/').pop();
var httpClient = Titanium.Network.createHTTPClient({
onload: function() {
var file = Titanium.Filesystem.getFile(Titanium.Filesystem.tempDirectory, filepath);
file.write(this.responseData);
try {
Ti.Android.currentActivity.startActivity(Ti.Android.createIntent({
action: Ti.Android.ACTION_VIEW,
type: 'application/pdf',
data: file.getNativePath()
}));
} catch (e) {
alert('No PDF reader found.');
}
}
});
httpClient.open('GET', url);
httpClient.send();
}
});
dialog.show();