How can I get photo src, from nativescript camera module?
public takePicture() {
cameraModule.takePicture().then(function(picture) {
console.log("Result is an image source instance");
var image = new imageModule.Image();
image.imageSource = picture;
console.dir(picture);
});
}
console.dir output:
=== dump(): dumping members ===
{
"android": {
"constructor": "constructor()function () { [native code] }"
}
}
=== dump(): dumping function and properties names ===
loadFromResource()
fromResource()
loadFromFile()
fromFile()
loadFromData()
fromData()
loadFromBase64()
fromBase64()
setNativeSource()
saveToFile()
height: 480
width: 640
=== dump(): finished ===
How do I get the image src ?
I want to upload it to firebase, so i need the src.
To upload to firebase, you need to upload the image via its path:
let imgsrc = this.imageSource.fromNativeSource(data);
let path = this.utils.documentsPath(randomName);
imgsrc.saveToFile(path, this.enums.ImageFormat.png);
this.firebase.uploadFile(path).then((uploadedFile: any) => {
this.appSettings.setString("fileName", uploadedFile.name);
this.router.navigate(['/soundcloud']);
this.LoadingIndicator.hide();
}, (error: any) => {
alert("File upload error: " + error);
});
}, (err: any) => {
alert(err);
});
Figured it out, this works:
public takePicture() {
cameraModule.takePicture().then((picture) => {
var image = new imageModule.Image();
image.imageSource = picture;
let savePath = fs.knownFolders.documents().path;
let fileName = 'img_' + new Date().getTime() + '_' + this.currentUserId.getValue() + '.' + enumsModule.ImageFormat.jpeg;
let filePath = fs.path.join( savePath, fileName );
picture.saveToFile(filePath, enumsModule.ImageFormat.jpeg);
this.photoService.uploadImage(filePath, fileName).then((data) => {
this._router.navigate(["/upload", fileName, this.currentUserId.getValue()]);
});
});
}
Related
I'm new to Vuejs. I want to have a form using which you can add products. The product image goes to firebase storage but how do I associate that image with the exact product in the database?
I've already set up my form, and created two methods. saveProduct() to save the products to the database and onFilePicked() to listen for changes in the input field and target the image and upload that to storage.
import { fb, db } from '../firebaseinit'
export default {
name: 'addProduct',
data () {
return {
product_id: null,
name: null,
desc: null,
category: null,
brand: null,
image: null,
}
},
methods: {
saveProduct () {
db.collection('products').add({
product_id: this.product_id,
name: this.name,
desc: this.desc,
category: this.category,
brand: this.brand
})
.then(docRef => {
this.$router.push('/fsbo/produkten')
})
},
onFilePicked (event) {
let imageFile = event.target.files[0]
let storageRef = fb.storage().ref('products/' + imageFile.name)
storageRef.put(imageFile)
}
}
}
what about this, you can use the filename, your images are going to be served as somefireurl.com/{your_file_name} on your product collection you can have an image prop with the imageFile.name.
methods: {
saveProduct (image = null) {
let productRef = db.collection('products').doc(this.product_id)
const payload = {
product_id: this.product_id,
name: this.name,
desc: this.desc,
category: this.category,
brand: this.brand
}
if (image) payload['image'] = image
return productRef
.set(payload, {merge: true})
.then(docRef => {
this.$router.push('/fsbo/produkten')
})
},
onFilePicked (event) {
let imageFile = event.target.files[0]
let storageRef = fb.storage().ref('products/' + imageFile.name)
storageRef.put(imageFile)
return this.saveProduct(imageFile.name)
}
}
That should be enough to get you started, maybe you want to try a different combination, or maybe you dont want to call saveProduct the way I set it, it's up to your use case but the idea is the same. Hope this can help you
I fixed it myself. Here's my solution. I don't know if it's technically correct but it works for my use case.
methods: {
saveProduct () {
let imageFile
let imageFileName
let ext
let imageUrl
let key
let task
db.collection('products').add({
product_id: this.product_id,
name: this.name,
desc: this.desc,
category: this.category,
brand: this.brand
})
.then(docRef => {
key = docRef.id
this.$router.push('/fsbo/produkten')
return key
})
.then(key => {
if(this.image !== null) {
this.onFilePicked
imageFile = this.image
imageFileName = imageFile.name
ext = imageFileName.slice(imageFileName.lastIndexOf('.'))
}
let storageRef = fb.storage().ref('products/' + key + '.' + ext)
let uploadTask = storageRef.put(imageFile)
uploadTask.on('state_changed', (snapshot) => {}, (error) => {
// Handle unsuccessful uploads
}, () => {
uploadTask.snapshot.ref.getDownloadURL().then( (downloadURL) => {
db.collection('products').doc(key).update({ imageUrl: downloadURL})
});
});
})
},
onFilePicked (event) {
return this.image = event.target.files[0]
}
}
Ionic refresher seems to be refreshing the page without being manually calling the doRefresh. I would like the refresher to only execute when the "pull down" action is done.
Seems like doRefresh is executed on "ionviewdidload" function automatically.
<ion-refresher (ionRefresh)="doRefresh($event);">
<ion-refresher-content
pullingText="Pull to refresh" pullingIcon="arrow-dropdown"
refreshingSpinner="circles"
refreshingText="..fetching">
</ion-refresher-content>
</ion-refresher>
home.ts
doRefresh(refresher) {
console.log('the current tab that is set = ' + this.tabSelId);
console.log('testing');
this.user = JSON.parse(window.localStorage.getItem('user'));
let self_ = this;
let devicePos = null;
let devicelat = null;
let devicelong = null;
Geolocation.getCurrentPosition().then((position) => {
// self_.loadingData(devicePos);
devicelat = position.coords.latitude;
devicelong = position.coords.longitude;
self_.get_all_posts(devicelat, devicelong, self_.tabSelId);
refresher.complete();
}, (err) => {
console.log('failed to get lat and long :' + err);
self_.get_all_posts(devicelat, devicelong, self_.tabSelId);
// self_.filter_posts_by_type(self_.tabSelId);
// loading.dismiss();
// refresher.complete();
});
}
on my ionviewdidload function (home.ts):
ionViewDidLoad(){
this.user = JSON.parse(window.localStorage.getItem('user'));
let self_ = this;
let devicePos = null;
console.log('the current tab that is set = '+this.tabSelId);
let devicelat = null;
let devicelong = null;
Geolocation.getCurrentPosition().then((position) => {
devicelat = position.coords.latitude;
devicelong = position.coords.longitude;
console.log('%c executing when position is got successfully ', 'background: #222; color: #bada55');
self_.get_all_posts(devicelat, devicelong, self_.tabSelId);
console.log('executing when position is got successfully');
}, (err) => {
console.log('failed to get lat and long :' + err);
devicelat = 28.318237;
devicelong = 111.168137;
self_.get_all_posts(devicelat, devicelong, self_.tabSelId);
});
is it the default behaviour when using
"ion-refresher"
I would like the refresher to only fire when "pull down" action is done.
Don't know why the doRefresh() function is being executed when the app is loaded (the first time only)
In your Html use like..
<ion-refresher slot="fixed" (ionRefresh)="doRefresh($event)">
<ion-refresher-content pullingIcon="arrow-dropdown" pullingText="Pull to refresh" refreshingSpinner="circles"
refreshingText="Refreshing...">
</ion-refresher-content>
</ion-refresher>
In .ts use like...
doRefresh(event) {
this.userPost();
setTimeout(() => {
event.target.complete();
}, 2000);
}
upload image using file transfer in ionic 3 works fine on android,
but give me error on iOS when try it in simulator ..
* this is the error:
My Ionic Code:
chooseImageFromGallery()
{
this.type="0"
const options: CameraOptions = {
quality: 60,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
saveToPhotoAlbum:true,
sourceType:0
}
this.camera.getPicture(options)
.then((imageData) => {
if (this.platform.is('ios'))
{
this.base64Image = imageData;
}
else
{
this.base64Image = imageData;
}
this.uploadimage(); // this function to upload img to server
},
(err) => {
}).then((path)=>{
})
}
uploadimage(){
this.photoSrc="";
this.translate.get("uploading Image...").subscribe(
value => {
this.sucesss=false
const fileTransfer: FileTransferObject = this.transfer.create();
let options: FileUploadOptions = {
fileKey: "file",
fileName:'test',
chunkedMode:false,
mimeType:"image/jpeg",
headers:{
Connection:"close"
},
httpMethod: "POST",
}
//------------ android ------------//
this.base64Image =this.base64Image
//------------ ios ------------//
//this.base64Image =this.base64Image.substring(28)
fileTransfer.upload(this.base64Image,encodeURI('mydomain/api/Product/upload'), options)
.then((data:any) => {
alert("upload success ")
}, (err) => {
this.translate.get( "error in upload Data").subscribe(
value => {
this.service.presentToast(value,2000)
}
)
})
})
}
using asp.net api2 .. My server Code :
[HttpPost]
[Route("upload")]
[AllowAnonymous]
public HttpResponseMessage uploadImage()
{
var request = HttpContext.Current.Request;
if (Request.Content.IsMimeMultipartContent())
{
foreach (string file in request.Files)
{
var postedFile = request.Files[file];
if (postedFile != null && postedFile.ContentLength > 0)
{
string root = HttpContext.Current.Server.MapPath("~/ServerImg");
root = root + "/" + postedFile.FileName;
postedFile.SaveAs(root);
//Save post to DB
return Request.CreateResponse(HttpStatusCode.Found, new
{
error = false,
status = "created",
path = root
});
}
else
{
return Request.CreateResponse(HttpStatusCode.NotFound, new
{
error = true
});
}
// var title = request.Params["title"];
}
// }
return null;
}
else
{
return Request.CreateResponse(HttpStatusCode.Forbidden, new
{
error = true
});
}
}
I spend more than 4 days.. but nothing is work for me ..
And this code works fine on Android but not iOS I don't know what's the wrong, I tried real iPhone and Xcode simulator and not worked
always upload error {"code":3... "http_status":500,..
Can anyone Help me please...
I'm trying evaluate the mime-type and the size of a image uploaded using nativescript-imagepicker. However seems like the module itself can't do it. How can I apply constraits to the file I'm uploading? (Like max size or just png or jpg)
There's my code:
const context = imagepicker.create({ mode: "single" });
context
.authorize()
.then(() => {
console.log('imagePicker.authorize...');
return context.present();
})
.then((selection) => {
if (!selection || !selection.forEach) {
console.log('Error on selection empty or not array:', selection);
return;
}
selection.forEach((selected) => {
this.processPhoto(selected);
});
}).catch((err) => {
.
.
.
Processing the image...
processPhoto (selectedPhoto: any) {
console.log('uploading photo to firebase', selectedPhoto);
this.firebaseService.getImagePickerLocalFilePath(selectedPhoto)
.then((localFilePath: string) => {
console.log('about to upload file:', localFilePath);
return this.firebaseService.uploadFile(localFilePath);
})
.catch((err) => {
this.isLoading = false;
this.messageService.handleErrorRes(err);
});
}
You will have to read the size & extension on File and prevent upload when they do not match your constraints.
const file = fileSystemModule.fromPath(localFilePath);
if (file.size <= YOUR_SIZE_LIMIT_IN_BYTES && file.extension.toLowerCase() === "png") {
// Upload
} else {
alert("File can't be uploaded");
}
Currently, I am implementing a chat. After user pressed a chat button, the app will navigate the user to the Chat component. The chat content will simply store in firebase and chatId is needed to identify which chat belongs to the user.
Since I don't know how to pass props during navigation, I decided to save the CurrentChatId in AsyncStorage. After navigated to the Chat component, it will get the CurrentChatId from AsyncStorage so that I can map the chat content with the firebase.
However, I got the error _this3.navigateTo is not a function with code below:
let ref = FirebaseClient.database().ref('/Chat');
ref.orderByChild("chatId").equalTo(chatId).once("value", function(snapshot) {
chatId = taskId + "_" + user1Id + "_" + user2Id;
if (snapshot.val() == null) {
ref.push({
chatId: chatId,
taskId: taskId,
user1Id: user1Id,
user2Id: user2Id,
})
}
try {
AsyncStorage.setItem("CurrentChatId", chatId).then(res => {
this.navigateTo('chat');
});
} catch (error) {
console.log('AsyncStorage error: ' + error.message);
}
}
The function navigateTo is copied from the demo app of NativeBase
import { actions } from 'react-native-navigation-redux-helpers';
import { closeDrawer } from './drawer';
const {
replaceAt,
popRoute,
pushRoute,
} = actions;
export default function navigateTo(route, homeRoute) {
return (dispatch, getState) => {
const navigation = getState().cardNavigation;
const currentRouteKey = navigation.routes[navigation.routes.length - 1].key;
dispatch(closeDrawer());
if (currentRouteKey !== homeRoute && route !== homeRoute) {
dispatch(replaceAt(currentRouteKey, { key: route, index: 1 }, navigation.key));
} else if (currentRouteKey !== homeRoute && route === homeRoute) {
dispatch(popRoute(navigation.key));
} else if (currentRouteKey === homeRoute && route !== homeRoute) {
dispatch(pushRoute({ key: route, index: 1 }, navigation.key));
}
};
}
You should bind this to the function that contains the try & catch. The best practice is to add this bind the constructor of the the component:
constructor(props) {
super(props);
this.myFunctoin = this.myfuction.bind(this);
}
Finally, I solved the problem. It is really because this.navigateTo('chat'); is inside function(snapshot)
ref.orderByChild("chatId").equalTo(chatId).once("value", function(snapshot) {
chatId = taskId + "_" + user1Id + "_" + user2Id;
if (snapshot.val() == null) {
ref.push({
chatId: chatId,
taskId: taskId,
user1Id: user1Id,
user2Id: user2Id,
})
}
}
try {
AsyncStorage.setItem("CurrentChatId", chatId).then(res => {
this.navigateTo('chat');
});
} catch (error) {
console.log('AsyncStorage error: ' + error.message);
}
Take it out from the function will solve the problem.