I tried to get Data of the Document but I only get Null.
Documentpicker is working, except: The Selected Data is NULL.
async openDocumentReader() {
try {
const res = await DocumentPicker.pick({
type: [DocumentPicker.types.csv],
});
console.log(
res.uri,
res.type,
res.name,
res.size,
);
if (res.name == null) {
Alert.alert('Document is Null');
}
} catch (err) {
if (DocumentPicker.isCancel(err)) {
//User canceld
} else {
throw err;
}
}
Any recommendations?
I found a solution:
I had to choose pickSingle for it.
try {
const res = await DocumentPicker.pickSingle({
type: [DocumentPicker.types.csv], mode : 'import', copyTo: 'documentDirectory',
});
var uri = res.uri;
var name = res.name;
var fileCopyUri = res.fileCopyUri;
console.log(JSON.stringify(res));
console.log(res.uri);
}
Or something like that.
Related
I am trying to upload a form which consists of a file as well. I have used document picker to select the file and then converted it into a blob, it works fine till here but when I try to upload the form to backend I get Cannot call a class as a function
I am not sure how to resolve this if anyone can pinpoint the error that would be great, thanks.
This is the error traceError
This is the code to Select File
const selectFile = async () => {
// Opening Document Picker to select one file
try {
const res = await DocumentPicker.pickSingle({
type: [DocumentPicker.types.allFiles],
});
console.log('res simple', res);
console.log('res : ' + JSON.stringify(res));
//fetch uri from the response
const fileUri = res.uri;
console.log('res : ' + fileUri);
setSingleFile(res);
// handleAcceptedFiles(res);
} catch (err) {
setSingleFile(null);
if (DocumentPicker.isCancel(err)) {
ToastAndroid.show('Canceled', ToastAndroid.SHORT);
} else {
alert('Unknown Error: ' + JSON.stringify(err));
throw err;
}
}
};
Creating Blob
useEffect(() => {
if (singleFile != null) {
getData();
}
}, [singleFile]);
const getData = async () => {
console.log("inside getData")
// console.log("singleFile",singleFile)
console.log("singlefile",singleFile.uri)
await fetch(singleFile.uri)
.then((response)=> {
console.log("response",response.blob())
// response.blob()
setBlob(response.blob())
}
)
.catch(err=>{
console.log(err);
});
}
And this is the function which is called when I click on upload button and where I am getting the error
const uploadData = async () => {
if (singleFile != null) {
const fileToUpload = singleFile;
console.log("blob",blob)
const data = new FormData();
data.append('Attachment',blob);
data.append(
"Address",
address
);
data.append(
"CNIC",
CNIC
);
data.append(
"Phone_Number",
number
);
data.append(
"Status",
"Pending Response"
);
data.append(
"Description",
description
);
data.append(
"Appointment_id", 'b082564a-67f0-4f3d-96d7-1a441e071ef4'
);
data.append(
"Patient_id", email
);
data.append(
"Amount", '4200'
);
console.log("data",data)
Alert("data",data)
let res = await axios.post(
`${url}/Finance/requestFA` , data,
{
headers: {
Authorization: `Bearer ${user.refresh_token}`
}
}
);
console.log("res in upload",res)
let responseJson = res.data
if (responseJson.status == 1) {
alert('Upload Successful');
}
} else {
// If no file selected the show alert
alert('Please Select File first');
}
};
I want to be able to call "setUser", but it's out of scope for some reason. This is in a MobX store that I've created. I'm sure it's something I'm doing fundamentally wrong, but I don't know what it is. Here's the code:
private setUser = (user: UserType) => {
this.userRegistry.set(user.Username, user);
}
loadUsersFromPoolGroups = () => {
this.loadingInitial = true;
try {
var congitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
const USER_POOL_ID = 'us-east-2_kWOEamV6i';
var params = {
UserPoolId: USER_POOL_ID
}
congitoidentityserviceprovider.listGroups(params, function(err, data) {
if (err) console.log(err, err.stack);
else {
data.Groups.forEach(group => {
var params = {
GroupName: group.GroupName,
UserPoolId: USER_POOL_ID
}
congitoidentityserviceprovider.listUsersInGroup(params, function(err1, data1) {
if (err1) console.log(err1, err1.stack);
else {
data1.Users.forEach((user) => {
this.setUser(user);
})
}
})
})
}
});
} catch (error) {
console.log('error loading users from pool groups', error)
}
}
I'm doing a similar thing in a different store with no issues.
private setSubmittal = (submittal: Submittal) => {
this.submittalRegistry.set(submittal.submittalId, submittal);
}
loadSubmittals = async () => {
this.loadingInitial = true;
try {
const submittals = await agent.Submittals.list();
submittals.data.forEach((submittal: Submittal) => {
this.setSubmittal(submittal);
})
this.setLoadingInitial(false);
} catch (error) {
console.log(error);
this.setLoadingInitial(false);
}
}
I expected to be able to call setUser and it won't let me.
this is the function which i used to decrypt the string with data and token :
import themis from "wasm-themis";
export const stringDec = async (str: string) => {
try {
var masterKey = Buffer.from(
"mykey",
"base64"
);
var mkey = Buffer.from(masterKey.toString("base64"));
var message = JSON.parse(str);
let symmetricKey = new themis.SymmetricKey(mkey)
let scellTP = themis.SecureCellTokenProtect.withKey(symmetricKey);
let encData = {
data: Buffer.from(message.hash, 'base64'),
token: Buffer.from(message.token, 'base64')
}
try {
let decrypted = scellTP.decrypt(encData.data, encData.token)
} catch (error) {
console.log("error", error);
}
} catch (error) {
console.error(error);
throw error;
}
};
Anyone have idea on same. Thanks in advance.
First of all sorry for the bad English
I'm trying to do a "tweet" system. I check if the link is true and has an image but if you put something like https://askhdkjahs.png the program thinks is an image and put in the embed giving an error
I need handle the error and put a default image or reply saying 'the image give a error'
thats my code
if (comando === `${prefix}atwt`) {
msg.delete({ timeout: 100 });
if (!argumento[0]) {
msg.reply('pon algo').then(msg => {
msg.delete({ timeout: 10000 });
}).catch(console.error);
}
else if(argumento !== null && argumento !== '') {
const TweetAnon = new Discord.MessageEmbed()
.setAuthor('Anonimo!', 'https://i.imgur.com/wSTFkRM.png')
.setColor('BLUE')
.setTimestamp();
const url = argumento[0].toString();
if (url.match(/^https.*\.(png|jpeg|jpg|gif|bmp)$/i)) {
TweetAnon.setImage(argumento[0]);
TweetAnon.setDescription(`**${argumento.slice(1).join(' ')}**`);
}
else{
TweetAnon.setDescription(`**${argumento.join(' ')}**`);
}
const msgEmbed = await msg.channel.send(TweetAnon).catch(TweetAnon.setImage('https://i.imgur.com/wSTFkRM.png'));
await msgEmbed.react('👍');
await msgEmbed.react('👎');
await msgEmbed.react('🔄');
}
}
I see something like that and I tried but doesn't work
if (comando === `${prefix}atwt`) {
const url = argumento[0].toString();
const TweetAnon = new Discord.MessageEmbed()
.setAuthor('Anonimo!', 'https://cdn.discordapp.com/attachments/769965806850670634/854834517709422602/anon.png')
.setColor('BLUE')
.setTimestamp();
msg.delete({ timeout: 100 });
try {
if (!url.match(/^https.*\.(png|jpeg|jpg|gif|bmp)$/i)) {
throw new Error('Invalid URL');
}
TweetAnon.setImage(argumento[0]);
TweetAnon.setDescription(`**${argumento.slice(1).join(' ')}**`);
}
catch (error) {
TweetAnon.setImage('https://i.imgur.com/wSTFkRM.png');
}
// else
// TweetAnon.setDescription(`**${argumento.join(' ')}**`);
// }
const msgEmbed = await msg.channel.send(TweetAnon).catch(err => console.log(err));
await msgEmbed.react('👍');
await msgEmbed.react('👎');
await msgEmbed.react('🔄');
}
You could check if the image exists like this:
function imageExists(image_url){
var http = new XMLHttpRequest();
http.open('HEAD', image_url, false);
http.send();
return http.status != 404;
}
Usage:
if(imageExists(argumento[0])){
TweetAnon.setImage(argumento[0]);
}
I have to upload images in the directory and save that name into a database using graphql resolver. When I upload an image and pass that image in resolver but I am getting an undefined value of image name. So how can I get the image name?
In the Below code, I saved information with file upload but a problem to get a file name after uploading an image. So how can I get the file uploaded file name?
const fs = require("fs");
function ProfileImage(argsprofilephoto) {
try {
argsprofilephoto.then(profilephoto => {
const {
createReadStream,
filename,
mimetype
} = profilephoto;
const fileStream = createReadStream();
fileStream.pipe(fs.createWriteStream(`./uploadedFiles/${filename}`));
console.log("filename=", filename);
return filename;
});
} catch (err) {
console.log(err);
}
}
export default {
Mutation: {
signUp: async (parent, args, {
models,
secret
}) => {
try {
let profimgnm = "";
let docimgnm = "";
// Prfile Photo Upload
if (args.profilephoto != "") {
profimgnm = ProfileImage(args.profilephoto);
console.log("profimgnm=", profimgnm);
}
if (args.documents != "") {
docimgnm = ProfileImage(args.documents);
console.log("docimgnm=", docimgnm);
}
let name = args.name;
let email = args.email;
let phone = args.phone;
let address = args.address;
let zipcode = args.zipcode;
let profilephoto = profimgnm;
let documents = docimgnm;
const user = await models.User.create({
name,
email,
phone,
address,
zipcode,
profilephoto,
documents
});
return user;
} catch (err) {}
}
}
};
I am getting this output.
profimgnm= undefined
docimgnm= undefined
filename= download.jpg
filename= dimg.jpg
Anyone, please give me a solution.
There are a few issues here. You are not returning the promise from ProfileImage async method. You should be doing something like:
function ProfileImage(argsprofilephoto) {
return argsprofilephoto.then(profilephoto => {
const {
createReadStream,
filename,
mimetype
} = profilephoto;
const fileStream = createReadStream();
fileStream.pipe(fs.createWriteStream(`./uploadedFiles/${filename}`));
console.log("filename=", filename);
return filename;
}).catch(e => {
// you might want to return some sensible default depending on your usecase, or let the error bubble up by not catching
console.log(e)
});
}
and in your resolver you need to wait for the promise to resolve:
if (args.profilephoto != "") {
// could still be undefined if the promise above failed on catch block returned nothing, but you get the idea
profimgnm = await ProfileImage(args.profilephoto);
console.log("profimgnm=", profimgnm);
}
if (args.documents != "") {
docimgnm = await ProfileImage(args.documents);
console.log("docimgnm=", docimgnm);
}