react-native-image-picker how to save image with customize filename - android

I am trying to develop an android application using react-native. and one of the requirement is to automatically save the capture image based on pre-defined filename programmatically. I am using react-native-image-picker.
The API of image-picker does not show way to save the image with per-defined filename programmatically. The tutorial I am using, does not show either.
Thanks a lot.

I have done it like this. This may help you out.
ImagePicker.launchCamera({},(responce)=>{
this.setState({
pickedImage: { uri: res.uri }
});
console.log(this.state.serverTime);
const file ={
uri : responce.uri,
//give the name that you wish to give
name :this.state.currentTimeInMilisec+'.jpg',
method: 'POST',
path : responce.path,
type : responce.type,
notification: {
enabled: true
}
}
console.log(file);
})
}

I have done as below. It is working fine.
ImagePicker.launchCamera({},(responce)=>{
const localTime = new Date().getTime();
const file ={
uri : responce.uri,
//give the name that you wish to give
name :localTime +'.jpg',
method: 'POST',
path : responce.path,
type : responce.type,
notification: {
enabled: true
}
}
console.log(file);
})
}

Related

How do I handover a image file in react native as URI, since require just returns a number?

I am looking for a solution to handover a image URI to a native module in Android.
The problem is, that when I require a image in react native, it just returns a number.
So I'd need to load the URI directly or some sort of string that can be converted to a file and afterwards to URI in android.
EDIT:
My images are loaded in a separat file like this:
{ sticker1: { uri: require('./Sticker_1.png'), path: './Sticker_1.png' } },
Afterwards I display items in a Flatlist like this:
renderItem(item) {
const itemIndex = item.index;
const itemKey = `sticker${itemIndex + 1}`;
const sticker = item.item[itemKey];
return (
<TouchableOpacity
onPress={() => this.handOverSticker()}
key={itemKey}
>
<Image source={sticker.uri} style={styles.previewImage} key={itemKey} />
</TouchableOpacity>
);
}
So far everything works.
handOverSTicker function looks like this:
handOverSticker(sticker) {
this.props.handleUseSticker(sticker);
}
The other component then takes care of the URI in a react native module in android and does other stuff. The problem is the received URI being the returned number by require.
Thank you!
constructor(props){
super(props);
let imgUrl = props.image ? { uri: props.image } : require("../assets/images/image.jpg");
this.state = { image: imgUrl };
}
In source of Image place this code:
source={this.state.image}

How to get the thumbnail of an Android gallery picture, in NativeScript?

I understand that Android automatically creates a thumbnail, for every picture taken by the camera. I need to be able to display that thumbnail.
I'm using nativescript-imagepicker plugin to select images. The plugin returns only the size and src of the selected image(s), for instance:
'/storage/emulated/0/DCIM/DSCF2060.jpg'
How could i use this src, to retrieve the corresponding thumbnail(is it even possible?).
The Android API is very confusing for me(not to mention the Java), so any help will be greatly appreciated.
Use ThumbnailUtils
export function onGetImageButtonTap(args) {
let context = imagepicker.create({
mode: "single"
});
context
.authorize()
.then(function () {
return context.present();
})
.then(function (selection) {
selection.forEach(function (selected) {
const size = layout.toDevicePixels(96);
const bitmap = android.media.ThumbnailUtils.extractThumbnail(android.graphics.BitmapFactory.decodeFile(selected.android),
size, size);
args.object.page.getViewById("thumbnailImg").src = fromNativeSource(bitmap);
});
}).catch(function (e) {
console.log(e)
});
}
Playground Sample

Ionic File Chooser URL issue

I am using this plugin for getting files
https://ionicframework.com/docs/native/file-chooser/
When I select a PDF file from Downloads folder it is giving me a URI like content://com.android.providers.downloads.documents/document/1015
But if i select another file like ZIP or PNG it resolves to a suitable path
content://com.android.providers.downloads.documents/document/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Fwws.zip
content://com.android.providers.downloads.documents/document/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Fopacity.png
How do I get the path from a file in the form of file://….
I have tried the following approaches with no success yet:
FilePath.resolveNativePath
and
normalizeURL
UPDATE:
Imports
import { File } from '#ionic-native/file';
import { FileChooser } from '#ionic-native/file-chooser'
import { FilePath } from '#ionic-native/file-path';
Code for file chooser:
getAndroidFile() {
this.fileChooser.open()
.then(uri => {
console.log("uri", uri);
this.file.resolveLocalFilesystemUrl(uri).then((files) => {
console.log("files", files);
}).catch((error) => { console.log("error", error) });
(<any>window).FilePath.resolveNativePath(uri, (result) => {
this.nativepath = result;
console.log("nativepath", this.nativepath);
}, (err) => {
console.log("err", err);
})
})
}
I have used it as Aaron suggested:
this.file.resolveLocalFilesystemUrl(uri).then((files)=>{
console.log("files",files);
}).catch((error) => { console.log("error", error) });
It still returns as:
filesystem: FileSystem {name: "content", root: DirectoryEntry}
fullPath: "/com.android.providers.downloads.documents/document/1015"
isDirectory: false
isFile: true
name: "1015"
nativeURL: "content://com.android.providers.downloads.documents/document/1015"
Which is the original url.
UPDATE 2:
getBase64Content(nativepath) {
let path = nativepath.substring(0, nativepath.lastIndexOf('/'));
let filename = nativepath.substring(nativepath.lastIndexOf('/'), nativepath.length);
filename = filename.replace("/", "");
console.log("path", path);
console.log("filename", filename);
this.file.readAsDataURL(path, filename)
.then(content => {
console.log('content1', content);
//this will be passed to web API
this.base64content = content;
})
.catch(err => {
console.log("err", err);
})
}
This base64 content is sent overthe to server via api and they convert it back to file.
UPDATE 3:
Sorry for late reply, really busy with another project.
Answers for Koken:
How are you testing this thing?
What command are you using for the execution?
ionic cordova run android
(I check the values by remote debugging using chrome.)
Android emulator? Android device?
Android Device. Redmi note 5 pro(MIUI 10, Android 8.1).
Also... what are the next steps after selecting the file?
This base64 content is sent over to server via api and they convert it back to file.
Hope you guys can help me. With code given. Thanks
you need resolveLocalFilesystemUrl from the FileManager Plugin
https://ionicframework.com/docs/native/file/#resolveLocalFilesystemUrl

How to Download and view profile picture in ionic 3 with sharepoint?

Iam new in ionic with sharepoint
I have developed a Mobile app using ionic3 with sharepoint.
Now i have to get user profile picture in my app.
I have tried these are the way can't achieve here is my tried code.
First way tried like this
Passing Url:-
"https://abc.sharepoint.com/sites/QA/_layouts/15/userphoto.aspx?size=M&accountname=admin#abc.onmicrosoft.com"
Second way tried like this
Passing Url:-
These url iam geting using people picker result. PictureURL property
"https://abc.sharepoint.com/User Photos/Profile Pictures/admin_abc_onmicrosoft_com_MThumb.jpg"
These Second method always return
401 UNAUTHORIZED
Above url using to call this method.
public downloadFile(url: string, fileName: string) {
let options = this._apiHeaderForImageURL();
this._http.get(url, options)
.subscribe((data) => {
//here converting a blob to base 64 For internal view purpose in image src
var reader = new FileReader();
reader.readAsDataURL(data.blob());
reader.onloadend = function () {
console.log("Base64", reader.result);
}
//Here Writing a blob file to storage
this.file.writeFile(this.file.externalRootDirectory, fileName, data.blob(), { replace: true })
.then((success) => {
console.log("File Writed Successfully", success);
}).catch((err) => {
console.log("Error While Wrinting File", err);
});
});
}
public _apiHeaderForImageURL() {
let headers = new Headers({ 'Content-Type': 'image/jpeg' });
headers.append('Authorization', 'Bearer ' + localStorage.getItem("token"));
let options = new RequestOptions({ headers: headers, responseType: 3 });
return options;
}
The first api call worked fine result also sucess but image not displayed properly. Thats the problem iam facing.
The result comes an default image like this only.
pls help me to achieve this. Any help warmly accepted.
Iam doning long time stuff to achieve this still i cant achieve pls give some idea.
Is any other way is available to get user picture in ionic 3 using sharepoint?

Cordova: How to move file to the Download folder?

THE SITUATION:
In my mobile app I need to download a file and store in the Download folder.
The download part is working fine.
The file is properly downloaded from the server and stored in the following folder:
file:///storage/emulated/0/Android/data/org.cordova.MY_APP_NAME.app/my_file.pdf
But the location is not really user-friendly.
To access it I have to go to: Internal storage / Android / data / org.cordova.MY_APP_NAME.app /
So I need to move it to the main Download folder.
The file transfer is what I don't manage to do.
I know that there are already several similar questions on SO.
I have tried them all but none really worked for me, I could never see the file in the actual Download folder.
PROJECT INFO:
I am using Quasar with Vuejs and Cordova.
PLATFORM:
For the moment I am working with Android. But ideally I am looking for a solution that works for both Android and IOS.
THE CODE:
The download code:
var fileTransfer = new FileTransfer() // eslint-disable-line
var uri = encodeURI('https://MY_SERVER_PATH')
fileTransfer.download(
uri,
cordova.file.externalApplicationStorageDirectory + 'my_file.pdf',
entry => {
console.log('download complete: ' + entry.toURL())
this.moveFile(entry.toURL())
},
error => {
console.log('download error source ' + error.source)
console.log('download error target ' + error.target)
console.log('download error code' + error.code)
},
false,
{
headers: {
'Authorization': 'Basic asdasdasdasdassdasdasd'
}
}
)
The File transfer code:
moveFile(fileUri) {
window.resolveLocalFileSystemURL(
fileUri,
fileEntry => {
let newFileUri = 'file:///storage/emulated/0/Download'
window.resolveLocalFileSystemURL(
newFileUri,
dirEntry => {
fileEntry.moveTo(dirEntry, 'new_filename.pdf', this.moveFileSuccess, this.moveFileError)
},
this.moveFileError)
},
this.moveFileError)
},
moveFileSuccess(entry) {
console.log('file move success')
console.log(entry)
},
moveFileError(error) {
console.log('file move error')
console.log(error)
}
THE QUESTION:
How can I move a file to the Download folder?
Thanks
EDIT:
This is the console log of the cordova.file object:
applicationDirectory: "file:///android_asset/"
applicationStorageDirectory: "file:///data/user/0/org.cordova.MY_APP_NAME.app/"
cacheDirectory:"file:///data/user/0/org.cordova.MY_APP_NAME.app/cache/"
dataDirectory: "file:///data/user/0/org.cordova.MY_APP_NAME.app/files/"
documentsDirectory: null
externalApplicationStorageDirectory: "file:///storage/emulated/0/Android/data/org.cordova.MY_APP_NAME.app/"
externalCacheDirectory: "file:///storage/emulated/0/Android/data/org.cordova.MY_APP_NAME.app/cache/"
externalDataDirectory: "file:///storage/emulated/0/Android/data/org.cordova.MY_APP_NAME.app/files/"
externalRootDirectory: "file:///storage/emulated/0/"
sharedDirectory: null
syncedDataDirectory: null
tempDirectory: null
Okay I managed to resolve it.
First of all is totally unnecessary to download and then move the file. It can just be directly downloaded in the desired direction.
The correct path (in my case) was this:
cordova.file.externalRootDirectory + 'download/' + 'my_file.pdf
that correspond to: file:///storage/emulated/0/download/my_file.pdf
and that means that to find the file inside the device you have to go to: Internal Storage / Download / my_file.pdf
Add the following value in the config.xml:
<preference name="AndroidPersistentFileLocation" value="Compatibility" />
<preference name="AndroidExtraFilesystems" value="files,files-external,documents,sdcard,root" />
It's important to check for permission using this cordova plugin: cordova-plugin-android-permissions
You can make a quick test like this:
let permissions = cordova.plugins.permissions
permissions.checkPermission(permissions.READ_EXTERNAL_STORAGE, checkPermissionCallback, null)
function checkPermissionCallback(status) {
console.log('checking permissions')
console.log(status)
}
Most probably the result is false. And that means that we have to request permission to the user:
permissions.requestPermission(successCallback, errorCallback, permission)
In this way it will appear the alert asking for permission.
THE CODE:
To put it all together, this is the working code:
let pdfPath = 'https://MY_SERVER_PATH'
let permissions = cordova.plugins.permissions
permissions.checkPermission(permissions.READ_EXTERNAL_STORAGE, checkPermissionCallback, null)
// Checking for permissions
function checkPermissionCallback(status) {
console.log('checking permissions')
console.log(status)
if (!status.hasPermission) {
var errorCallback = function () {
console.warn('Storage permission is not turned on')
}
// Asking permission to the user
permissions.requestPermission(
permissions.READ_EXTERNAL_STORAGE,
function (status) {
if (!status.hasPermission) {
errorCallback()
} else {
// proceed with downloading
downloadFile()
}
},
errorCallback)
} else {
downloadFile()
}
}
function downloadFile() {
let filePath = cordova.file.externalRootDirectory + 'download/' + 'my_file.pdf'
let fileTransfer = new window.FileTransfer()
let uri = encodeURI(decodeURIComponent(pdfPath))
// Downloading the file
fileTransfer.download(uri, filePath,
function (entry) {
console.log('Successfully downloaded file, full path is ' + entry.fullPath)
console.log(entry)
},
function (error) {
console.log('error')
console.log(error)
},
false
)
}
var fileTransfer = new FileTransfer() // eslint-disable-line
var uri = encodeURI('https://MY_SERVER_PATH')
var fileURL = "///storage/emulated/0/Download";
fileTransfer.download(
uri,
fileURL+ 'your_file.pdf',
entry => {
console.log('download complete: ' + entry.toURL())
this.moveFile(entry.toURL())
},
error => {
console.log('download error source ' + error.source)
console.log('download error target ' + error.target)
console.log('download error code' + error.code)
},
false,
{
headers: {
'Authorization': 'Basic asdasdasdasdassdasdasd'
}
}
)
you can directly save downloaded file to your path
Try above code and let me know if its work.
cordova.file.externalApplicationStorageDirectory.
For that path you do not need to request any permission in manifest or require any permission at all.
But for others like external storage and so you need them.
You are #1244 with this problem this year.
Google for runtime permissions.
You can than directly download to the Download directory.

Categories

Resources