document-viewer in ionic not working not open file - ionic-framework

Hello I use followring code not working How to Resole It..
fileTransfer.download(url, path + 'abcd.pdf').then((entry) => {
let localUrl = entry.toURL();
const toast = this.toast.create({
message: 'Download Complted',
duration: 20000,
position: 'top',
closeButtonText: 'OK',
showCloseButton: true,
});
toast.present();
this.document.viewDocument(localUrl, 'application/pdf', {});
}, (error) => {
// handle error
console.log("In error");
console.log(error);
alert(JSON.stringify(error));
});
How to be it working!!

Did you add document viewer plugin in you project? please see this link https://ionicframework.com/docs/native/document-viewer/ you can find commands.
ionic cordova plugin add cordova-plugin-document-viewer
npm install --save #ionic-native/document-viewer
Then you have to pass options also in viewDocument functions
fileTransfer.download(url, path + 'abcd.pdf').then((entry) => {
let localUrl = entry.toURL();
const toast = this.toast.create({
message: 'Download Complted',
duration: 20000,
position: 'top',
closeButtonText: 'OK',
showCloseButton: true,
});
toast.present();
const options: DocumentViewerOptions = {
title: 'My PDF'
}
this.document.viewDocument(localUrl, 'application/pdf', options);
}, (error) => {
// handle error
console.log("In error");
console.log(error);
alert(JSON.stringify(error));
});
Hope this will work for you!

Related

Error while Uploading Image to Mongodb using Gridfs and Graphql

Im trying to upload an image to mogodb using graphql and gridfs. When trying to do i'm facing a error :
" JSON Parse error: Unexpected identifier "This" "
I'm not sure what I've done wrong in the code.
Can anyone help me figure out where I've gone wrong in the implementation
This is the part for uploading Image
const selectProfilePic = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [2, 3],
quality: 1,
});
handleImagePicked(result);
};
const handleImagePicked = async (result: ImagePicker.ImagePickerResult) => {
try {
if (result.cancelled) {
alert("Upload cancelled");
return;
} else {
console.log("In HERE ::: 76");
const lastIndex = result.uri.lastIndexOf("/") + 1;
console.log(result);
const file = new ReactNativeFile({
uri: result.uri,
name: result.uri.substring(lastIndex),
type: "image/png",
});
setAvatar(result.uri);
console.log(file); // This result is getting printed.
await singleUpload({ // I think the Upload function is not getting called.
variables: {
file,
},
});
}
} catch (e) {
console.log(e);
alert("Upload failed");
}
};
Resolver Function
singleUpload: async (_, { file }, context) => {
const {db, user, hhhhhh, gfs} = context;
console.log(gfs);
const res = uploadFn({ file },gfs);
console.log(res);
Apollo.tsx File
const uploadLink = createUploadLink({
uri: CLIENT_HTTP_URI,
});
// splitLink is defined here
export const client = new ApolloClient({
link: ApolloLink.from([authLink, splitLink]),
cache: new InMemoryCache(),
});
Have created StorageEngine.js File with this code
const storage = new GridFsStorage({
url: DB_URI,
file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if(err) { return reject(err); }
const fileName = buf.toString('hex') + path.extname(file.originalname);
const fileInfo = {
fileName,
bucketName: 'uploads'
};
resolve(fileInfo);
});
});
}
});
const upload = multer({storage});
const uploadFn = async ({file}, bucket) => {
console.log(file);
const { createReadStream, name, type, encoding } = await file;
const uploadStream = bucket.openUploadStream(name, {
contentType: type
});
// console.log(uploadStream);
return new Promise((resolve, reject) => {
createReadStream()
.pipe(uploadStream)
.on('error', reject)
.on('finish', () => {
console.log(uploadStream.id);
resolve(uploadStream.id);
});
});
}

How to share a video directly to facebook/instagram through a link as video which can be directly played using react-native

How to share a video directly to Facebook/Instagram/twitter through a link using react-native. I am using react-native-share to share videos on Instagram/Facebook but that is getting shared as a link, but I want to share them as a video as TikTok does.
How can I achieve that? I know it is able by converting it to base 64, so are there any libraries which convert links to base 64 directly? Else I would need to download it first then retrieve it and then convert to base 64 then share it.
Please help!
Will Answer how I did it if some one needs the complete code:
shareURL = async (socialMedia) => {
let facebook = socialMedia === 'facebook'
let twitter = socialMedia === 'twitter'
const { video, uploadingStatus } = this.state;
this.setState({ isSliderModalVisible: true }, async () => {
let uploadOptions = { fileCache: true, appendExt: 'mp4', timeout: 60000, indicator: true, IOSBackgroundTask: true, }
const res = await RNFetchBlob.config(uploadOptions).fetch('GET', video, {})
.progress((received, total) => {
this.setState({ uploadingStatus: (received / total) * 100 })
console.log('Progress', (received / total) * 100);
})
const filePath = res.path(); //to delete video
const base64String = await res.base64();
const url = `data:video/mp4;base64,${base64String}`;
await RNFetchBlob.fs.unlink(filePath); //deleted the video from path of celebfie.
this.setState({ isSliderModalVisible: false })
setTimeout(() => {
const shareOptions = {
title: 'Celebfie',
message: hashtags,
subject: 'Sharing my intro video which I recorded in Celebfie.',
url: url,
type: 'video/mp4',
social: facebook ? Share.Social.FACEBOOK : twitter ? Share.Social.TWITTER : Share.Social.INSTAGRAM
};
Share.shareSingle(shareOptions).then((res) => this.setState({ sharedVideoToSocialNetwork: true }))
.catch((err) => { Global.customToast('Video sharing failed.', 'failure') })
})
}, 1000);
}
Answering my own question here it is how it works :
shareURL = async (socialMedia) => {
let facebook = socialMedia === 'facebook'
let twitter = socialMedia === 'twitter'
const { video, uploadingStatus } = this.state;
this.setState({ isSliderModalVisible: true }, async () => {
let uploadOptions = { fileCache: true, appendExt: 'mp4', timeout: 60000, indicator: true, IOSBackgroundTask: true, }
const res = await RNFetchBlob.config(uploadOptions).fetch('GET', video, {})
.progress((received, total) => {
this.setState({ uploadingStatus: (received / total) * 100 })
console.log('Progress', (received / total) * 100);
})
const filePath = res.path(); //to delete video
const base64String = await res.base64();
const url = `data:video/mp4;base64,${base64String}`;
await RNFetchBlob.fs.unlink(filePath); //deleted the video from path of Sexy lady.
this.setState({ isSliderModalVisible: false })
setTimeout(() => {
const shareOptions = {
title: 'Sexy Lady',
message: hashtags,
subject: 'Sharing my intro video which I recorded in Celebfie.',
url: url,
type: 'video/mp4',
social: facebook ? Share.Social.FACEBOOK : twitter ? Share.Social.TWITTER : Share.Social.INSTAGRAM
};
Share.shareSingle(shareOptions).then((res) => this.setState({ sharedVideoToSocialNetwork: true }))
.catch((err) => { Global.customToast('Video sharing failed.', 'failure') })
})
}, 1000);
}
you can do like this :
Share.open(
{
message: `I have successfully Completed this course`,
title: 'Share',
url: 'file:///documents..',
type: 'video/mp4',
},
{
// Android only:
dialogTitle: 'Share',
// iOS only:
excludedActivityTypes: ['com.apple.UIKit.activity.PostToTwitter'],
},
);

Fail to save user to mongodb

If I remain this code, the program still working, my image will upload backend to frontend normally
router.post('/admin/register', upload.single('avatar'), async (req, res) => {
// Handle add image by multer
... handel file upload from front-end
return res.json({ avatar: newFullPath });
}
);
I started save user to mongoDB and error occur
router.post('/admin/register', upload.single('avatar'), async (req, res) => {
// Handle add image by multer
... handel file upload from front-end
//Handle add user to database
const user = {
...JSON.parse(req.body.user),
avatar: newFullPath
}; // { first_name: 'John', last_name: 'Wick', avatar: .... }
const { error } = Validation.adminRegisterValidation(user);
if (error) {
return res.json({ error: error.details[0].message });
} // working as I expected
const emailExist = await User.findOne({ email: user.email });
if (emailExist) {
return res.json({ error: 'Email already exist!' });
} // working as I expected
// If I commented this block of code, program still run as I expected, but if I don't do
// that, the program crashed ( Error: Below images )
const hashedPassword = bcrypt.hashSync(user.password, 10);
const addUser = new User({
first_name: user.first_name,
last_name: user.last_name,
avatar: user.avatar
});
await addUser.save();
return res.json({ avatar: newFullPath });
}
);
This project in my Github repository: This project in Github
Error shows in console
Error in Network

hapi lab AssertionError [ERR_ASSERTION]: Plugin crumb already registered

i'm not sure why i am receiving this. I am trying to create a simple test while using #hapi/crumb. i am only registering it once in my server.js.
const Path = require("path");
const hapi = require("hapi");
const inert = require("inert");
const vision = require("vision");
const Ejs = require("ejs");
const Crumb = require("#hapi/crumb");
const Blankie = require("blankie");
const Scooter = require("#hapi/scooter");
const routes = require("./routes");
// Configure the server
const server = hapi.Server({
host: "0.0.0.0",
port: process.env.PORT || 3000,
routes: {
files: {
relativeTo: Path.join(__dirname, "..", "public")
},
state: {
parse: true,
failAction: "ignore"
},
security: {
xframe: true,
noOpen: false
},
cors: {
origin: ["banglarelief.org"],
headers: ["Authorization"], // an array of strings - 'Access-Control-Allow-Headers'
exposedHeaders: ["Accept"], // an array of exposed headers - 'Access-Control-Expose-Headers',
additionalExposedHeaders: ["Accept"], // an array of additional exposed headers
maxAge: 60,
credentials: true // boolean - 'Access-Control-Allow-Credentials'
}
}
});
const plugins = async () => {
const pluginsToRegister = [
inert,
vision,
require("hapi-mobile-views"),
{ plugin: Crumb, options: { cookieOptions: { isSecure: false } } },
Scooter,
{
plugin: Blankie,
options: {} // specify options here
}
];
await server.register(pluginsToRegister);
};
const init = async () => {
await plugins();
server.state("player", {
ttl: null,
clearInvalid: true,
isSecure: false
});
server.views({
engines: { ejs: Ejs },
path: `${__dirname}/views`,
layout: "layout"
});
await server.route(routes);
return server;
};
const start = async () => {
try {
await init();
await server.start();
} catch (err) {
console.log(err);
process.exit(1);
}
};
module.exports = { init, start };
My test file is very basic and i have tried to move around where the start should be called but it keep throwing same error.
'use strict';
const Lab = require('#hapi/lab');
const { expect } = require('#hapi/code');
const { afterEach, beforeEach, describe, it } = exports.lab = Lab.script();
const { init, start } = require('../src/server');
let server = start();
describe('GET /', () => {
//let server;
//server = start();
beforeEach(async () => {
//server = start();
});
afterEach(async () => {
//await server.stop();
});
it('responds with 200', async () => {
const res = await server.inject({
method: 'get',
url: '/'
});
expect(res.statusCode).to.equal(200);
});
});
I have been following https://hapijs.com/tutorials/testing?lang=en_US
The solution seems to work if you break up your plugins function into two parts. One part will init 3rd party plugins like #Hapi/*. The other function will init your 1st party plugins that you wrote. You will only init the 3rd party plugins in your start function.
It's critical that you include { once: true } because that will prevent your error. It will only initialize the plugin once, which will prevent your error. You cannot always specify { once: true } on 3rd party plugins. Thus, we have to handle that a different way. Since we moved all the 3rd party plugins to their own function, which is invoked on start, that should prevent 3rd party plugins from causing an issue of being reinitialized.
const hapiPlugins = async () => {
const pluginsToRegister = [
inert,
vision,
require("hapi-mobile-views"),
{ plugin: Crumb, options: { cookieOptions: { isSecure: false } } },
Scooter,
{
plugin: Blankie,
options: {} // specify options here
}
];
};
const myPlugins = async () => {
await server.register([
allOfMyPlugins...
],
{
once: true //critical so that you don't re-init your plugins
});
};
const init = async () => {
server.state("player", {
ttl: null,
clearInvalid: true,
isSecure: false
});
server.views({
engines: { ejs: Ejs },
path: `${__dirname}/views`,
layout: "layout"
});
await server.route(routes);
return server;
};
const start = async () => {
try {
await hapiPlugins();
await init();
await server.start();
} catch (err) {
console.log(err);
process.exit(1);
}
};
Then, you should be able to call init in your test's before function. Use that server object to inject.

Ionic: Android - Image from Camera is not uploading to server with FileTransfer

I am trying to pick a image from photo gallary and upload to the server.
I have a PHP script to receive the file and copy to the server location. I have tested this script with Postman. It works perfectly.
I have a provider to upload the image to the PHP script. The code snippet for upload function is below.
upload(imageData) {
let posturl = APIURL + 'message/upload';
const fileTransfer: FileTransferObject = this.transfer.create();
let options1: FileUploadOptions = {
fileKey: 'file',
fileName: 'name.jpg',
headers: {}
}
return new Promise((resolve, reject) => {
fileTransfer.upload(imageData, posturl, options1)
.then((data) => {
resolve(data);
}, (err) => {
alert(JSON.stringify(err));
reject(err.message);
});
});
}
TS code for picking the image and calling the provider is:
pickimage()
{
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.imageURI = imageData;
}, (err) => {
// Handle error
});
}
TS code for picking the image and calling the provider:
this.messageService.upload(this.imageURI).then((result) => {
this.responseData = result;
if (this.responseData.status=="success")
{
this.mediaurl = this.responseData.mediaurl;
}
},
(err) => {
alert("Not able to send image");
});
The file is not getting uploaded. The alert(JSON.stringify(err)) in the provider returns null.
I am testing this with DevApp.
Any help?