Unable to share Image of Product in React Native Share - react-native

I am working on sharing the product description, url and image using react-native-share. But, it is not working and showing the attachment as somename.null.
I am getting the base64 image from response. Code is written below.
shareProduct = () => {
console.log(this.props.productDetails);
let { name, product_url, base64 } = this.props.productDetails;
const shareOptions = {
title: "Testing APP",
url: product_url,
message: "This is the testing. Please check",
subject: name
};
if( base64 !== "" && base64 !== undefined ){
shareOptions.url = base64;
shareOptions.type = 'image/jpeg';
}
Share.open(shareOptions)
.then(res => {})
.catch(err => {
console.log(err);
});
};
Please help me to find issue where I am wrong.

You need to change url in Options :
Share.open(
{
message: "This is the testing. Please check",
title: 'Share',
url: product_url,
type: 'image/jpg',
activityItemSources: [
{
linkMetadata: {image: `data:image/jpg;base64,${product_url}`},
},
],
},
{
// Android only:
dialogTitle: 'Share',
// iOS only:
excludedActivityTypes: ['com.apple.UIKit.activity.PostToTwitter'],
},
);

Related

Getstream.io with React Native

I suffer from uploading image to getstream service. And it doesn't upload image.
Here is my code. I get the following error.
Here is my code.
const filter = { type: 'messaging', members: { $in: [userInfo.id] } };
const sort = [{ last_message_at: -1 }];
let channels;
await chatClient.queryChannels(filter, sort, {
watch: false,
state: true,
}).then((response) => {
channels = response;
})
const file = this.state.avatar;
let avatarURI;
channels[0].sendImage(file).then((response) => {
avatarURI = response.file;
console.log(avatarURI);
})

How to append array of images to server using formdata react native?

I’m trying to post an item to my server. I’m using React Native for my front end and Laravel as my back-end. I have tried it many times but it keeps giving me Network request failed. Though I am trying it on postman and it works fine.
this is my demo code:
var dummyArray = [
{
type: "image/jpeg",
uri: "file:///storage/emulated/0/Android/data/com..../files/Pictures/4cbc8fa0-5978-42a6-89ab-ea9639cb43e4.jpg",
name: ("file:///storage/emulated/0/Android/data/com.../files/Pictures/4cbc8fa0-5978-42a6-89ab-ea9639cb43e4.jpg").split("/").pop()
},
{
type: "image/jpeg",
uri: "file:///storage/emulated/0/Android/data/com..../files/Pictures/e3de766a-5c67-4926-9a56-93b0c989970a.jpg",
name: ("file:///storage/emulated/0/Android/data/com..../files/Pictures/e3de766a-5c67-4926-9a56-93b0c989970a.jpg").split("/").pop()
}
]
const formdata = new FormData();
formdata.append('images[]', this.state.imageArray);
I have resolve similar and like below:
submitImage(images = [{ uri: "", fileName: "", type: "" }]) {
const oFormData = new FormData();
images.map((val) => {
oFormData.append("image", {
uri: val.uri,
type: val.type,
name: val.fileName
});
});
return axios.post(PostServiceUrl, oFormData);
}
You are passing whole array as a single param which is wrong. You should add all the images one by one in form data
let formData = new FormData();
if (images.length > 0) {
images.forEach((element) => {
formData.append('images', element);
});
} else {
formData.append('images', undefined);
}
i have resolved my query with following code:
Object.keys(dummyArray).forEach((item, i) => {
formdata.append(`images[${item}]`,
{
uri: dummyArray[item].uri,
name: dummyArray[item].name,
type: dummyArray[item].type
}
);
})

Issue in uploading files with react native with axios

I am trying to upload files to server in react-native application with axios as http handler.
My code stands as:
let promises = [];
const body = new FormData();
console.log(body);
body.append('device_name', this.state.deviceInfo.DeviceName);
body.append('device_id', this.state.deviceInfo.DeviceID);
body.append('device_ip', this.state.deviceInfo.DeviceIP);
body.append('device_os', this.state.deviceInfo.DeviceOS);
body.append('upload_type', 'user');
body.append('user_name', user.Email);
body.append('file1', {
uri: this.state.newImageUrl.uri,
name: 'test.jpg',
type: 'image/jpg',
});
promises.push(
apiUploadDocs(body)
.then(res => {
profileImageName = res[0].NewFileName;
})
.catch(err => {
console.log('this error', err);
}),
);
My apiUploadDocs is as :
export const apiUploadDocs = body => {
return new Promise((resolve, reject) => {
axios
.post(ApiRoutes.uploadDocs, body,{headers:{'content-Type': `multipart/form-data`}})
.then(res => {
console.log('upload success');
console.log(res);
})
.catch(err => {
console.log('upload error', err);
if (err.response) {
}
reject(Constant.network.networkError);
});
});
};
Every assigned variable has correct values upon logging and the api is working good when I try to upload from Postman.
But this snippet here results in an error which is undefined when logged.
I have tried trimming the 'file://' from the uri, as suggested by some answers here in stackoverflow.
I cant figure it out. Can you help me finding whats wrong here??
PS: The body when logged is:
{
"_parts":[
[
"device_name",
"sdk_gphone_x86"
],
[
"device_id",
"xxxxxxxxxxxxx"
],
[
"device_ip",
"10.0.2.xx"
],
[
"device_os",
"goldfish_x86"
],
[
"upload_type",
"user"
],
[
"user_name",
"xxxxx#gmail.com"
],
[
"file1",
[
"Object"
]
]
]
}
if it is of any reference.
I've found a link to uploading image in react-native.
https://aboutreact.com/file-uploading-in-react-native/
This might be of some help to you.
let uploadImage = async () => {
//Check if any file is selected or not
if (singleFile != null) {
//If file selected then create FormData
const fileToUpload = singleFile;
const data = new FormData();
data.append('name', 'Image Upload');
data.append('file_attachment', fileToUpload);
let res = await fetch(
'http://localhost//webservice/user/uploadImage',
{
method: 'post',
body: data,
headers: {
'Content-Type': 'multipart/form-data; ',
},
}
);
let responseJson = await res.json();
if (responseJson.status == 1) {
alert('Upload Successful');
}
} else {
//if no file selected the show alert
alert('Please Select File first');
}
};

React-Native 62.2 code image upload Error : network error

I am using React-Native two days back After React-Native version upgrading to 0-62.2, I encountered many problems.
Among them important one is image upload error getting [Error:Network error ]
Before upgrading the React-native my code is working fine
Below code is working fine for me for multiple image upload before upgrading to React-Native 0.62.2 but now i am getting [Error: Network error]
constructor() {
super();
this.state = {
uploadPercentage: 0,
}
}
// upload Files upload_Files = async () => {
upload_File() {
if (this.validate_Fields()) {
const { image, images, files, description, userId, size } = this.state;
console.log('AddPost Screen : upload_File:', 'userId:', userId, 'Files:', files, 'description:', description)
// this.setState({ error: '', loading: true });
if (this.state.type === 'image/jpeg') {
console.log('AddPost Screen : upload_ files :', files);
const formData = new FormData();
formData.append('user_id', userId);
formData.append('description', description);
// formData.append('files[]', files);
for (let i = 0; i < files.length; i++) {
formData.append('files[]', {
name: files[i].path.split('/').pop(),
type: files[i].mime,
uri: Platform.OS === 'android' ? files[i].path : files[i].path.replace('file://', ''),
});
}
// upload percentage progress bar ******************************************************
const options = {
onUploadProgress: (progressEvent) => {
const { loaded, total } = progressEvent;
let percent = Math.floor((loaded * 100) / total)
console.log(`${loaded}kb of ${total}kb | ${percent}%`);
if (percent < 100) {
this.setState({ uploadPercentage: percent })
}
}
}
axios.post(API_URL + '/fileuploadapi/uploadPost', formData, options, {
headers: { "Content-type": "multipart/form-data" }
}).then((response) => {
console.log(JSON.parse(JSON.stringify(response.status)));
// upload percentage progress
this.setState({ uploadPercentage: 100 }, () => {
setTimeout(() => {
this.setState({ uploadPercentage: 0 })
}, 1000);
})
this.cleanupImages();
Alert.alert('Upload Post Successfully');
}).catch((error) => {
console.log(error);
this.cleanupImages();
Alert.alert('image Upload Post Failed , Try again !');
});
}
}
}
// clear files data
cleanupImages() {
this.setState({
description: '',
image: null,
images: null,
// video: '',
files: '',
uploadPercentage: 0,
})
ImagePicker.clean().then(() => {
console.log('removed tmp images from tmp directory');
}).catch(error => {
alert(error);
});
}
If anyone know the solution please let me know ...
I just found the solution for the React-Native 62.2 upgrading error for image upload Error
[Error: network error]
Just remove the file "ReactNativeFlipper.java" from debug/java folder
File Location :
android/app/src/debug/java/com/appname/ReactNativeFlipper.java

Convert Image to base64 in react native

I have used react-native-image-picker and now I select image from the Photo library. To send the that image to API I have to convert it first into base64 and then into byte array. I have the filepath in response.uri. How do I do it?
When I did console.log(response) I am getting this in result
'Response = ', {
fileSize: 6581432,
longitude: -17.548928333333333,
uri: 'file:///Users/shubhamb/Library/Developer/CoreSimulator/Devices/B58314DF-F0A9-48D2-B68A-984A02271B72/data/Containers/Data/Application/63143214-8A03-4AC8-A79C-42EC9B82E841/tmp/2AACBC57-0C07-4C98-985E-154668E6A384.jpg',
fileName: 'IMG_0003.JPG',
latitude: 65.682895,
origURL: 'assets-library://asset/asset.JPG?id=9F983DBA-EC35-42B8-8773-B597CF782EDD&ext=JPG',
type: 'image/jpeg',
height: 2002,
width: 3000,
timestamp: '2012-08-08T18:52:11Z',
isVertical: false,
}
Since you're using react-native-image-picker, it already returns the Base64 value in its response
ImagePicker.showImagePicker(options, (response) => {
const base64Value = response.data;
});
Documentation for the response
I suddenly ran into this issue while updating my app. What I found is that previous react-native-image-picker used to provide base64 as response.data. But now there is an includeBase64 in the options object so that you can control whether you need the base64 data or not. So my code became something like the following
captureTradeLicenseImage() {
let options = {
maxHeight: 250,
maxWidth: 350,
includeBase64: true //add this in the option to include base64 value in the response
}
ImagePicker.launchCamera(options, (response) => {
console.log('Response = ', response)
if (response.didCancel) {
console.log('User cancelled image picker')
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error)
}
else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton)
}
else if (response.fileSize > 5242880) {
Alert.alert(
"Nilamhut Say\'s",
"Oops! the photos are too big. Max photo size is 4MB per photo. Please reduce the resolution or file size and retry",
[
{ text: "OK", onPress: () => console.log('ok Pressed') }
],
{ cancelable: false }
)
}
else {
this.setState({tradeLicenseImageData: response.base64}) //access like this
}
})
}
The standalone expo FileSystem package makes this simple:
const base64 = await FileSystem.readAsStringAsync(photo.uri, { encoding: 'base64' });
https://docs.expo.io/versions/latest/sdk/filesystem/
https://github.com/expo/expo/tree/master/packages/expo-file-system
As 2019-09-27 this package handles both file:// and content:// uri's
I'm too late but if I can help others that is looking how to get the base64 data from an image:
In the options object you have to set the base64 option to true, like this:
const options = {
title: 'Choose an Image',
base64: true
};
ImagePicker.launchImageLibrary(options, response => {
console.log(response.data);
});
As simple as that:
import { CameraOptions, ImagePickerResponse, launchCamera } from 'react-native-image-picker';
Wrap in your component:
const [b64, setB64] = useState<string>("");
const manageImage = async (response: ImagePickerResponse) => {
if (response.didCancel) {
return;
} else if (response.assets) {
if (response.assets?.length > 0) {
setB64(response.assets[0].base64 ? response.assets[0].base64 : "");
}
}
}
launchCamera(options, (response) => {
manageImage(response);
});