this.file.dataDirectory was showing null, I have installed cordova in globally but still, I am not able to find any solution.where did I make a mistake?
download() {
const fileTransfer: FileTransferObject = this.transfer.create();
const url = 'http://www.example.com/file.pdf';
fileTransfer.download(url, this.file.dataDirectory + 'file.pdf').then((entry) => {
console.log('download complete: ' + entry.toURL());
}, (error) => {
// handle error
});
}
use
cordova.file.dataDirectory
instead of
this.file.dataDirectory
Related
I am working on an app and I am using expo, I want to make sure each user can upload an image to firebase, and later publish this image on the profile page.
Using expo this is how I upload images:
const pickImage = async () => {
let pickerResult = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
console.log(pickerResult);
handleImagePicked(pickerResult);
};
the result in the console is:
Object {
"cancelled": false,
"height": 312,
"type": "image",
"uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252Fallergyn-app-77bfd368-65fd-43f9-8c34-9c35cef42c25/ImagePicker/daaa229c-c352-4994-ae18-ca2dbb3534ce.jpg",
"width": 416,
}
and this is how I upload to the firebase:
const handleImagePicked = async (pickerResult) => {
try {
if (!pickerResult.cancelled) {
setImage(pickerResult.uri);
await uploadImageAsync(pickerResult.uri);
console.log("done");
}
} catch (e) {
console.log(e);
alert("Upload failed, sorry :(");
} finally {
}
};
async function uploadImageAsync(uri) {
const blob = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
resolve(xhr.response);
};
xhr.onerror = function (e) {
console.log(e);
reject(new TypeError("Network request failed"));
};
xhr.responseType = "blob";
xhr.open("GET", uri, true);
xhr.send(null);
});
const ref = firebase
.storage()
.ref()
.child("images" + Math.random());
const snapshot = await ref.put(blob);
// We're done with the blob, close and release it
blob.close();
return await snapshot.ref.getDownloadURL();
}
this code works it saves the path of the image this: "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252Fallergyn-app-77bfd368-65fd-43f9-8c34-9c35cef42c25/ImagePicker/daaa229c-c352-4994-ae18-ca2dbb3534ce.jpg" in the firebase under user collection using the uid of the user.
I am not sure if this is good, because I want to make sure the image itself is uploaded to firebase, I saw some threads in StackOverflow regarding this issue either too old or no answers, so I am hoping to get some sort of solution to what I need to do.
if I use
const ref = firebase
.storage()
.ref()
.child("images" + Math.random());
.putFile(uri);
this tells me that putFile is not a function. the same with put(uri)
Try this one. This function returns the path of the saved image from firebase which you will store in the user's document instead.
const handleImagePicked = async (pickerResult) => {
if (!pickerResult.cancelled) {
setImage(pickerResult.uri);
const result = await uploadImageAsync(pickerResult.uri);
if(result) {
console.log('success');
//save the result path to firestore user document
return;
}
alert("Upload failed, sorry :(");
}
};
export const uploadImageAsync = async (uri: string) => {
let filename = uri;
if (Platform.OS === 'ios') {
filename = uri.replace('file:', '');
}
const ext = filename.split('.').pop();
const path = `images/${id}.${ext}`;
const ref = firebase.storage().ref(path);
try {
const response = await fetch(filename);
const blob = await response.blob();
await ref.put(blob);
return path;
} catch {
return null;
}
};
This worked for me , using rn-fetch-blob
import launchImageLibrary from 'react-native-image-picker';
import RNFetchBlob from 'rn-fetch-blob';
import storage from '#react-native-firebase/storage';
const pickImage = () => {
let options = {
mediaType: 'photo',
quality: 0.5,
};
launchImageLibrary(options, (response) => {
console.log('Response = ', response);
uploadImagePicked(response);
});
};
const uploadImagePicked = (response) => {
if (response.fileName) {
const fileName = response.fileName;
var storageRef = storage().ref(`receiptImages/${fileName}`);
RNFetchBlob.fs.readFile(response.uri , 'base64')
.then(data => {
storageRef.putString(data, 'base64', {contentType:"image/jpg"})
.on(
storage.TaskEvent.STATE_CHANGED,
snapshot => {
console.log("snapshot: " + snapshot.state);
console.log("progress: " + (snapshot.bytesTransferred / snapshot.totalBytes) * 100);
if (snapshot.state === storage.TaskState.SUCCESS) {
console.log("Success");
}
},
error => {
console.log("image upload error: " + error.toString());
},
() => {
storageRef.getDownloadURL()
.then((downloadUrl) => {
console.log("File available at: " + downloadUrl);
})
})
})
.catch(error => {
console.log(error);
})
}
else {
console.log("Skipping image upload");
}
}
Thank you for taking the time to read this,
I have a little problem with node-soap, so basically I'm trying to verify the identity of the client before sending back a response, after following the documentation I found the server.authenticate function.
server.authenticate = async function (security: any) {
const binarySecurityTokenAsBase64String = security.BinarySecurityToken.$value;
const pemKeyFromRequestAsString = "-----BEGIN CERTIFICATE-----" + "\n" + binarySecurityTokenAsBase64String.replace(/(.{64})/g, "$1\n") + "\n" + "-----END CERTIFICATE-----";
const success = await validateCertificate(pemKeyFromRequestAsString);
if (success) {
return true;
} else {
winston.warn("Failed to validate Certificate - Either Certificate Verification with CA Chain Failed or the system encountered an error");
return false;
}
};
That's where I do my verification business and return true or false based on the result:
const success = await validateCertificate(pemKeyFromRequestAsString);
My problem is, no matter what is the result, I still get the response back, on the logs, everything is fine and confirm that the verification failed, maybe this because of Async/Sync stuff.. I'm really new to Javascript/Typescript World, any help would be greatly appreciated.
Here is my a preview of my code:
try {
const myService = {
Calculate_Service: {
Calculate_Port: {
multiply: function(args, callback) {
const a = 1;
try {
winston.debug("Reached the multiply Function");
const n = args.a * args.b;
callback({
multiplicationResult : n
});
} catch (e) {
winston.error(e);
throw {
Fault: {
Code: {
Value: "soap:Sender",
Subcode: { value: "rpc:BadArguments" }
},
Reason: { Text: JSON.stringify(e) },
statusCode: 500
}
};
}
},
}
}
}
const xml = fs.readFileSync(AppConfiguration.responseServerWsdlPath, "utf8");
app.use(bodyParser.raw({
type: function () {
return true;
}, limit: "5mb"
}));
app.listen(port, async function () {
winston.info("Express server listening on port " + port);
const server = ArcNodeSoap.listen(app, "/calculatorService", myService, xml);
server.authenticate = async function (security: any) {
const binarySecurityTokenAsBase64String = security.BinarySecurityToken.$value;
const pemKeyFromRequestAsString = "-----BEGIN CERTIFICATE-----" + "\n" + binarySecurityTokenAsBase64String.replace(/(.{64})/g, "$1\n") + "\n" + "-----END CERTIFICATE-----";
const success = await validateCertificate(pemKeyFromRequestAsString);
if (success) {
return true;
} else {
winston.warn("Failed to validate Certificate - Either Certificate Verification with CA Chain Failed or the system encountered an error");
return false;
}
};
server.log = function (type, data) {
winston.debug("type: " + type);
winston.debug(JSON.stringify(data));
};
server.on("headers", function (headers, methodName) {
//More debug stuff;
winston.debug("****** HEADERS **********");
winston.debug(JSON.stringify(headers));
winston.debug("methodName: " + methodName);
winston.debug("*************************")
});
});
} catch (err) {
winston.error(err);
}
I appreciate the time guys, thank you!
I finally fixed my problem, if anyone has the same problem with the async/sync code:
I fixed it by using the Async method from the documentation
server.authenticate = function (security: any, callback): any {
//Get the Binary Security Token coming from the request as a Base 64 String
const binarySecurityTokenAsBase64String = security.BinarySecurityToken.$value;
//Creating a new certificate with header, footer and line breaks from the binarySecurityTokenAsBase64String
const pemKeyFromRequestAsString = "-----BEGIN CERTIFICATE-----" + "\n" + binarySecurityTokenAsBase64String.replace(/(.{64})/g, "$1\n") + "\n" + "-----END CERTIFICATE-----";
//Validate the certificate
//This is an async wrapper where I added all my verification steps;
validateCertificateWrapper(pemKeyFromRequestAsString).then((authorized: boolean) => {
//If the certificate is valid
if (authorized) {
winston.info("Verification successfully Passed");
return callback(true);
} else { //If the certificate is invalid
winston.error("Failed to validate Certificate");
return callback(false);
}
}, () => {
winston.error("Failed to validate Certificate");
return callback(false);
} );
};
const getUser = async (user) => {
const body = await snekfetch.get('https://www.website.com/api/public/users?name=' + user);
const userInfo = JSON.parse(body.text);
const r = await snekfetch.get('https://www.website.com/api/public/users/' + userInfo.uniqueId + '/profile');
const extraUserInfo = JSON.parse(r.text);
const _message = await client.users.get('437502925019807744').send({ files: ['https://www.website.nl/avatar-imaging/avatarimage?figure=h' + userInfo.figureString + '.png'] });
const avatarImage = _message.attachments.first().url;
return { userInfo, extraUserInfo, avatarImage };
};
getUser(args[0]).then((result) => {
message.channel.send(`${result.userInfo.name}`);
}).catch(function(result) {
console.log(result.userInfo.name);
});
Here I am trying to use 3 API's, however it always goes to the catch, even if one exists and other don't, I tried to only use result.userInfo.name to only use the first API, also in the catch I use the first one, then I tried a name that only has the first API but not the second one however I still get: TypeError: Cannot read property 'name' of undefined because it looks at the second API as well, what else can I do to handle with this situation? So basically how can I only catch errors for the first API
edit: I also tried:
if (extraUserInfo.user.name) {return { userInfo, extraUserInfo, avatarImage };}
else {return { userInfo, avatarImage };}
Fixed it with a try catch
try {
const r = await snekfetch.get('https://www.website.com/api/public/users/' + userInfo.uniqueId + '/profile');
const extraUserInfo = JSON.parse(r.text);
return {
userInfo,
extraUserInfo,
avatarImage
};
} catch (error) {
const extraUserInfo = {
'error': 'not-found'
};
return {
userInfo,
extraUserInfo,
avatarImage
};
}
};
getUser(args[0]).then((result) => {
console.log(result.extraUserInfo.error === 'not-found' ? result.userInfo.name : result.extraUserInfo.user.name);
}).catch((error) => {
console.log(error);
});
I am trying to convert an image file to blob but get the error below:
{"code":2, "message":"SECURITY_ERR"}
Any idea why this might be happening? I tried a lot of online resources but really could not find out what is going on.
I have the following code:
choose(){
this.filechooser.open().then((uri)=>{
this.file.resolveLocalFilesystemUrl(uri).then((newurl)=>{
let dirPath = newurl.nativeURL;
alert(dirPath);
let dirPathsegments = dirPath.split('/')
dirPathsegments.pop();
dirPath = dirPathsegments.join('/');
this.file.readAsArrayBuffer(dirPath, newurl.name).then((buffer)=>{
let blob = new Blob([buffer], {type: "image/jpeg"});
alert('blob creation success');
}, Error=>{
alert('Blob Error '+ JSON.stringify(Error));
});
});
},Error=>{
alert('Error Choosing File ' + Error);
});
}
Is there any other way to convert the file into a blob?
The current APIs that I am using only accepts Binary or Multipart attachments
It works. Tested on ionic 2 & 3
uploadFile() {
this.fileChooser.open().then((url) => {
(<any>window).FilePath.resolveNativePath(url, (nativeFilepath) => {
this.readFileFromStorage(nativeFilepath);
}
)
})
}
readFileFromStorage(nativeFilepath) {
let fileName = this.getfilename(nativeFilepath);
let fileExt = fileName.substring(fileName.lastIndexOf('.') + 1);
let blogType = { type: 'image/'+fileExt };
(<any>window).resolveLocalFileSystemURL(nativeFilepath, (res) => {
res.file((resFile) => {
var reader = new FileReader();
reader.readAsArrayBuffer(resFile);
reader.onloadend = (evt: any) => {
var imgBlob = new Blob([evt.target.result], blogType);
//Upload blob to firebase
this.uploadToFirebase(imgBlob,fileName);
}
})
})
}
getfilename(filePath){
let fileName : string;
fileName = filePath.replace(/^.*[\\\/]/, '')
return fileName;
}
uploadToFirebase(fileBlob, name) {
let storage = firebase.storage();
storage.ref('images/' + name).put(fileBlob).then((d) => {
alert("Done");
}).catch((error) => {
alert("Error: " + JSON.stringify(error));
});
}
I am working on a React project and I am using the Cordova plug-in for the first time. I have it taking pictures correctly but now I want to store them locally on the device using persistent storage. I found pretty good documentation but for some reason cannot get this code to work. If anyone could help I would really appreciate it!
Here is my function:
takePicture() {
navigator.camera.getPicture(
imageData => {
this.setState({image: imageData});
let path = 'filesystem:' + imageData;
window.resolveLocalFileSystemURL(
path,
(entry) => {
window.requestFileSystem(
LocalFileSystem.PERSISTENT,
50 * 1024 * 1024,
(fileSys) => {
//The folder is created if doesn't exist
fileSys.root.getDirectory(
'Observation Photos',
{create:true, exclusive: false},
directory => {
let d = new Date(),
n = d.getTime(),
filename = n + '.jpg';
entry.moveTo(directory, filename, (entry) => {
Photos.insert(entry);
}, handleError);
},
handleError
);
},
handleError
);
}, (error) => {
console.log(error);
}
);
}, message => {
console.log(message);
}
);
}
Here is an example of the paths I am passing in:
filesystem:file:///storage/emulated/0/Android/data/com.id1b9kkvri4mj2dnqkf9p/cache/1470171102308.jpg
Returns this in the inspector:
FileError {code: 5}
value of Path should be Android/data/com.id1b9kkvri4mj2dnqkf9p/cache/1470171102308.jpg;
so it needs a small change:
let path = imageData.replace("file:///storage/emulated/0/","");