I want to send image in react-Native-Gifted-chat like sending text. I am novice in react-native.
I have already used react-native-image-picker for pick a image from physical device, now I am unable to render image in message[].
You can call the onSend method of GiftedChat with an object as a parameter. Just pass an object with image as key. For example
onSend({ image: "https://picsum.photos/id/237/200/300" });
you can use this
import DocumentPicker from 'react-native-document-picker';
install this library first
then simply choose the file from the document picker
use this function
onAttatchFile = async () => {
try {
const res = await DocumentPicker.pick({
type: [DocumentPicker.types.allFiles],
});
// console.log(res);
let type = res.name.slice(res.name.lastIndexOf('.') + 1);
if (
res.type == 'doc' ||
res.type == 'application/pdf' ||
res.type == 'image/jpeg' ||
res.type == 'image/png' ||
res.type == 'image/jpg' ||
res.type == 'application/msword' ||
type == 'docx'
) {
this.setState({slectedFile: res}, () => this.onSendWithImage());
} else {
alert(`${type} files not allowed`);
}
} catch (err) {
//Handling any exception (If any)
if (DocumentPicker.isCancel(err)) {
//If user canceled the document selection
// alert('Canceled from single doc picker');
} else {
//For Unknown Error
// alert('Unknown Error: ' + JSON.stringify(err));
throw err;
}
}
};
use this function when you want to send the image
onSendWithImage() {
let imageData = {
name: this.state.slectedFile.name,
type: this.state.slectedFile.type,
size: this.state.slectedFile.size,
uri: this.state.slectedFile.uri,
};
var formData = new FormData();
formData.append('type', 2);
formData.append('senderId', this.state.senderData.id),
formData.append('recieverId', this.state.reciverData._id),
formData.append('message', imageData);
post('sendMessage', formData).then(res =>
res.success ? this.msjSendSuccess(res) : this.msjSendFailure(res),
);
}
talk with your backend and say to him /her to send the image in the image key
complete enjoy React native
Related
I am using ngx-dropzone with angular 8. I have used ngx-dropzone for uploading and it works but this time I want to load images from a specific list to dropzone. Here is my code.
<ngx-dropzone (change)="onSelect($event)">
<ngx-dropzone-label>Select/Drop images here!</ngx-dropzone-label>
<ngx-dropzone-image-preview ngProjectAs="ngx-dropzone-preview" [removable]="true" (removed)="onRemove(f)" *ngFor="let f of files" [file]="f">
<ngx-dropzone-label></ngx-dropzone-label>
</ngx-dropzone-image-preview>
</ngx-dropzone>
Here is my onSelect event which bindimages and push them into files array list.
onSelect(event) {
this.alertService.clear();
console.log(event.addedFiles);
this.files.push(...event.addedFiles);
if (this.files.length > 4) {
this.alertService.error('Please select only four images for each service.');
this.files = [];
} else {
this.bindImages();
}
}
bindImages() {
this.alertService.clear();
this.imageList = [];
this.files.forEach((x) => {
const file = x;
if (file.type.split('/')[0] !== 'image') {
this.alertService.error('Please select image to proceed further.');
return false;
}
if (file.size > 5242880) {
this.alertService.error('Image size must be equal to or less then 5 MB.');
return false;
}
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const val = reader.result as string;
const items = [{Serviceimage: val, ServiceId: this.serviceId, SaloonId: this.saloonId}];
this.imageList.push(...items);
};
reader.onerror = (error) => {
console.log('Error: ', error);
return;
};
});
}
Here is the my api codes which returns me the list of images with base64 string
getImages() {
this.alertService.clear();
this.imageModel.SaloonId = this.saloonId;
this.imageModel.ServiceId = this.serviceId;
this.apiService.Create('Saloon/getServiceImages', this.imageModel).subscribe(
resp => {
if (resp.length > 0) {
// Here to load Images to dropzone.
}
console.log(this.files);
},
error => {
this.alertService.error('Error getting images. Please contact admin.');
},
() => { console.log('complete'); }
);
}
This image returns me the following list.
I use Ionic 4 and Angular 7 with PHP as Back-end.
I am trying to upload files (images/videos/PDFs/audio).
Is there a general way to send it.
I tried to send image using camera plugin it returns the URI and it works on the app using img tag.
But I can't get the file it self to send it using formData
openCamera() {
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.imageData = imageData;
this.image = (<any>window).Ionic.WebView.convertFileSrc(imageData);
// this.image works fine in img tag
this.sendMsg(this.image);
}, (err) => {
// Handle error
alert('error ' + JSON.stringify(err));
});
}
sendMsg(file?) {
const data = new FormData();
data.set('group_id', this.groupId);
data.set('text', this.msg);
if (file) {
data.set('file', this.image);
data.set('text', '');
}
this.messeges.push(data);
this._messengerService.postMsg(data).subscribe(
res => {
console.log('res ', res);
if (res.success === true) {
console.log('data added ', res);
}
}
);
}
I want the use the URI to get the actual file
Ionic Native plugin will return only base64. As per your question, you need to convert formdata. so, You need to convert base64 to formdata externally.
dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], { type: mimeString });
}
and
profileUpdate(options) {
this.camera.getPicture(options).then((imageData) => {
let base64Image = 'data:image/jpg;base64,' + imageData;
let data = this.dataURItoBlob(base64Image);
let formData = new FormData();
formData.append('profile', data, "filename.jpg");
//here you pass the formdata to to your API
})
I'm writing Webrtc chrome desktop app by accessing 2 camera simultaneously using latest Chrome Windows version.
Accessing camera list by navigator.mediaDevices.enumerateDevices() is ok but accessing these device by their specific id using navigator.mediaDevices.getUserMedia not work.
It only occurs sometimes. But no error in the catch.
So, I tried navigator.mediaDevices.getUserMedia is really exists or not.
if (navigator && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
}
Yes, it was.
Just not getting any log info in calling navigator.mediaDevices.getUserMedia()
getVideoSources_ = function() {
return new Promise(function(resolve, reject) {
if (typeof navigator.mediaDevices.enumerateDevices === 'undefined') {
alert('Your browser does not support navigator.mediaDevices.enumerateDevices, aborting.');
reject(Error("Your browser does not support navigator.mediaDevices.enumerateDevices, aborting."));
return;
}
requestVideoSetTimeout = 500;
navigator.mediaDevices.enumerateDevices().then((devices) => {
// get the list first by sorting mibunsho camera in first place
for (var i = 0; i < devices.length; i++) {
log("devices[i]", JSON.stringify(devices[i]));
log("devices[i].label", devices[i].label);
if (devices[i].kind === 'videoinput' && devices[i].deviceId && devices[i].label) {
if (devices[i].label.indexOf("USB_Camera") > -1) {
deviceList[1] = devices[i];
} else {
deviceList[0] = devices[i];
}
}
}
// request video by sorted plan
for (var i = 0; i < deviceList.length; i++) {
requestVideo_(deviceList[i].deviceId, deviceList[i].label, resolve, reject);
requestVideoSetTimeout = 1000; // change requestVideoSetTimeout for next video request
}
}).catch((err) => {
log("getVideoSources_:" + err.name + ": " + err.message);
reject(Error("getVideoSources_ catch error"));
});
});
}
getVideoSources_().then(function(result) {
....
}).catch(function(err) {
....
});
function requestVideo_(id, label, resolve, reject) {
if (navigator && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
log("navigator.mediaDevices.getUserMedia found!");
navigator.mediaDevices.getUserMedia({
video: {
deviceId: {exact: id},
width: 640,
height: 480,
frameRate: {
ideal: 20,
max: 20
}
},
audio: false}).then(
(stream) => {
log("***requestVideo_", id);
log("***requestVideo_", label);
log("***requestVideo_", stream);
// USB_Camera is face camera
if (label.indexOf("USB_Camera") > -1) {
log("***requestVideo_001");
myStream2 = stream;
log("***requestVideo_myStream2", myStream2);
} else {
log("***requestVideo_002");
myStream = stream;
log("***requestVideo_myStream", myStream);
getUserMediaOkCallback_(myStream, label);
}
resolve("###Video Stream got###");
stream.getVideoTracks()[0].addEventListener('ended', function(){
log("***Camera ended event fired. " + id + " " + label);
endedDevice[id] = label;
});
},
getUserMediaFailedCallback_
).catch((error) => {
log('requestVideo_: ' + error.name);
reject(Error("requestVideo_ catch error" + error.name));
});
}
}
function getUserMediaFailedCallback_(error) {
log("getUserMediaFailedCallback_ error:", error.name);
alert('User media request denied with error: ' + error.name);
}
#Kaiido is right, resolve is called in a for-loop here, which is all over the place, and before all the code has finished. Any error after this point is basically lost.
This is the promise constructor anti-pattern. In short: Don't write app code inside promise constructors. Don't pass resolve and reject functions down. Instead, let functions return promises up to you, and add all app code in then callbacks on them. Then return all promises so they form a single chain. Only then do errors propagate correctly.
See Using promises on MDN for more.
I want when pick photo from device if size of photo > 10 MB or video >100 MB it will not pick. So I use RNFetchBlobStat to get size of photo and video.
When I get detail info of photo from device it show size = 1.42MB but when RNFetchBlobStat return size is 3466195 B. (ImagePicker fileSize have same result)
Here is my code
const MAX_SIZE_PHOTO = 10485760 //10*1024*1024
const MAX_SIZE_VIDEO = 104857600//100*1024*1024
getSizeImg = (type, source) => {
RNFetchBlob.fs.stat(source.uri.replace('file:///', '').replace('file://', '').replace('file:/', ''))
.then((stats) => {
console.log("file size", stats.size)
if (type === 'video') {
if (stats.size > MAX_SIZE_VIDEO) {
Alert.alert(null, "This video is too large to be uploaded")
error()
return
}
uploadVideo(source, completeHandler, progressHandler, error, diary_id, token)
} else {
if (stats.size > MAX_SIZE_PHOTO) {
Alert.alert(null, "This image is too large to be uploaded")
error()
return
}
uploadImage(source)
}
})
.catch((err) => {
console.log("getSize", err)
error(err)
})
}
export let choiceImage = (openLibrary, completeHandler, progressHandler, error, closeLibrary, diary_id, token) => {
console.log("choiceImage", diary_id, token)
ImagePicker.showImagePicker(optionsImage, (response) => {
if (response.didCancel) {
closeLibrary();
}
else if (response.error) {
error()
}
else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
}
else {
// openLibrary(response.uri, 'image');
let source = {
uri: response.uri,
name: response.fileName ? response.fileName : 'image.png',
type: 'image/*',
};
getSizeImg('image', source);
}
});
}
const isIOS = Platform.OS === 'ios';
/**
* FUNCTION CHOICE VIDEO FROM LIBRARY
* #param func
*/
export let choiceVideo = (openLibrary, completeHandler, progressHandler, error, closeLibrary, diary_id, token) => {
ImagePicker.showImagePicker(optionsVideo, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
closeLibrary();
}
else if (response.error) {
error();
}
else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
}
else {
// openLibrary(isIOS ? response.uri : 'file://' + response.path, 'video');
let source = {
uri: response.uri,
name: response.fileName ? response.fileName : "video.mp4",
type: 'video/*',
};
getSizeImg('video', source);
}
});
}
Why RNFetchBlobStat return size photo unlike size when get detail info photo from device?
How I can fix it?
You're right. tat, it seems it is not meant to return the size of file recursively. fs.stat does not return correct images size. The issue still open under react-native-fetch-blob lib.
Basically, you can do this by checking the files' size recursively but if we're going to do this in native it might take some time. Here is some code line may help you :
How can I calculate the size of a folder?
https://github.com/kfiroo/react-native-cached-image/blob/master/ImageCacheProvider.js
I need to modify the Kurento group call example from Link
to send only audio if one participant has no camera. Right now only audio is received when a camera is used. When only a microphone is available I receive a DeviceMediaError.
I managed to filter whether a camera device is connected or not and then send only audio, but this doesn't work. Maybe the participant should've an audio tag instead of a video tag?
EDIT: It's only working on Firefox and not in Chrome. Any ideas?
in file - https://github.com/Kurento/kurento-tutorial-java/blob/master/kurento-group-call/src/main/java/org/kurento/tutorial/groupcall/UserSession.java.
change following line -
sender.getOutgoingWebRtcPeer().connect(incoming, MediaType.AUDIO);
and set offer media constraints to video:false in browser js file.
updated code -
let constraints = {
audio: true,
video: false
};
let localParticipant = new Participant(sessionId);
participants[sessionId] = localParticipant;
localVideo = document.getElementById('local_video');
let video = localVideo;
let options = {
localVideo: video,
mediaConstraints: constraints,
onicecandidate: localParticipant.onIceCandidate.bind(localParticipant),
configuration : { iceServers : [
{"url":"stun:74.125.200.127:19302"},
] }
};
localParticipant.rtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendonly(options, function(error) {
if (error) {
return console.error(error);
}
localVideoCurrentId = sessionId;
localVideo = document.getElementById('local_video');
localVideo.src = localParticipant.rtcPeer.localVideo.src;
localVideo.muted = true;
this.generateOffer(localParticipant.offerToReceiveVideo.bind(localParticipant));
});
server.js code
function join(socket, room, callback) {
let userSession = userRegister.getById(socket.id);
userSession.setRoomName(room.name);
room.pipeline.create('WebRtcEndpoint', {mediaProfile : 'WEBM_AUDIO_ONLY'}, (error, outgoingMedia) => {
if (error) {
console.error('no participant in room');
if (Object.keys(room.participants).length === 0) {
room.pipeline.release();
}
return callback(error);
}
// else
outgoingMedia.setMaxAudioRecvBandwidth(100);
add media profile parameter on server side while joining room.
function getEndpointForUser(userSession, sender, callback) {
if (userSession.id === sender.id) {
return callback(null, userSession.outgoingMedia);
}
let incoming = userSession.incomingMedia[sender.id];
if (incoming == null) {
console.log(`user : ${userSession.id} create endpoint to receive video from : ${sender.id}`);
getRoom(userSession.roomName, (error, room) => {
if (error) {
return callback(error);
}
room.pipeline.create('WebRtcEndpoint', {mediaProfile : 'WEBM_AUDIO_ONLY'}, (error, incomingMedia) => {
if (error) {
if (Object.keys(room.participants).length === 0) {
room.pipeline.release();
}
return callback(error);
}
console.log(`user: ${userSession.id} successfully create pipeline`);
incomingMedia.setMaxAudioRecvBandwidth(0);
incomingMedia.getMaxAudioRecvBandwidth(0);
add media profile parameter when accepting call.
hope this helps.