I am trying to upload images to my server using
"cordova-plugin-file-transfer": "^1.7.1",
"#ionic-native/file-transfer": "^5.0.0",
component.ts
takePicture() {
const options: CameraOptions = {
quality: 50,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
targetWidth: 500,
targetHeight: 500,
saveToPhotoAlbum: false
};
this.camera.getPicture(options)
.then((imageData) => this._img.uploadImage(imageData))
.catch(err => console.log(err));
}
imageProvider.ts
import { FileTransfer, FileUploadOptions, FileTransferObject } from "#ionic-native/file-transfer/ngx";
...
uploadImage(img) {
const url = `${this.apiURL}/images/upload`;
// File for Upload
var targetPath = img;
var options: FileUploadOptions = {
fileKey: 'image',
chunkedMode: false,
mimeType: 'multipart/form-data'
};
const fileTransfer: FileTransferObject = this.transfer.create();
fileTransfer.upload(targetPath, url, options)
.then(() => {
console.log('good');
}, (err) => {
console.log('bad');
})
}
I get this error in logcat Android Studio:
"TypeError: Cannot read property 'constructor' of undefined"
I have found that the code works well till it reaches this line
const fileTransfer: FileTransferObject = this.transfer.create();
You are using the wrong native plugin version, For Ionic 3, you should use version 4.
ionic cordova plugin add cordova-plugin-file-transfer
npm install --save #ionic-native/file-transfer#4
And also, don't append ngx at the end of the import.
import { FileTransfer, FileUploadOptions, FileTransferObject } from '#ionic-native/file-transfer';
For your future reference, If you are using Ionic 3, follow Ionic v3 docs instead of latest docs.
V3 docs: https://ionicframework.com/docs/v3/native/file-transfer/
you might be missing this line after the imports:
constructor(private transfer: FileTransfer, private file: File) { }
that's at least what the documentation suggests.
Related
I'm trying to upload images from mobile gallery to cloudinary.
I have followed the logic in documentation of uploading photos from angular to cloudinary that I found in this link.
And I used File Transfer plugin to upload photos from ionic3 app to cloudinary.
this is the upload() function :
upload() {
const fileTransfer: FileTransferObject = this.transfer.create();
let options: FileUploadOptions = {
fileKey: 'testName',
fileName: 'test',
mimeType : "text/plain",
headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
params:{upload_preset:'preset'}
};
let url = 'https://api.cloudinary.com/v1_1/<cloud_name>/image/upload';
if (this.imageURI) {
fileTransfer.upload(this.imageURI[0], encodeURI(url), options)
.then((data) => {
console.log('uploaded heeere data', JSON.stringify(data))
}, (err) => {
console.log('errorrrr', JSON.stringify(err))
})
}
}
this.imageUri[0] is a photo as base 64
and in app.module.ts I have specified the cloudinary configuration :
import { CloudinaryConfiguration, CloudinaryModule } from "#cloudinary/angular-5.x";
import { Cloudinary } from "cloudinary-core";
#NgModule({
declarations: [....],
imports: [
BrowserModule,
HttpClientModule,
CloudinaryModule.forRoot({Cloudinary}, {
cloud_name: "<cloud_name>",
upload_preset: 'preset',
api_key:'<api_key>'
} as CloudinaryConfiguration),
]
.......
})
But I failed to upload.
There's no error shown.. Just a message: File Name is too long
I don't know if the connection is established or not and is it cloudinary who's refusing files with long names or what?
Could some one please help me how to debug to see where the problem is? or could someone help me fixing this?
Thanks a lot.
you should send image name not base64 encode ,the server read the base64 as name file ,so you try should send file name in first parameter
I have an app that allows a user to select a photo from the gallery or take a photo via camera. I am trying to display an image that was taken via camera and it works fine, it returns a file path like
file:///Users/ray/Library/Developer/CoreSimulator/Devices/C8202B3B-300B-4819-8CD3-4C4AA690CE7C/ data/Applications/D82BF64E-6DD1-4645-B637-BCF65001FD29/tmp/cdv_photo_003.jpg
but when I try to select a photo from a gallery it shows a broken image thumbnail, and it turns a file path like.
content://com.android.providers.media.documents/document/image%3A21
Ionic CLI Version: PRO 4.2.1
Cordova Verion: 8.0.0
NPM Version: 6.4.1
Node.js version: 8.11.3
Platform: Android
I've also tried searching for a solution but it didn't work or I am still doing something wrong
Unable to load image when selected from the gallery on Android in phonegap
https://www.raymondcamden.com/2014/10/10/Cordova-the-Camera-plugin-AngularJS-and-Ninja-Cats
ionic cordova : how to display an image in img tag from android gallery when i get content:// url from filechooser plugin
Unable to load image when selected from the gallery on Android 4.4 (KitKat) using PhoneGap Camera Plugin
Some of them suggests using this code
if (imageURI.substring(0,21)=="content://com.android") {
photo_split=imageURI.split("%3A");
imageURI="content://media/external/images/media/"+photo_split[1];
}
but this solution is not that robust cause not all of the image sources returns the same file path that contains 'content://com.android' like the photos that came from Google Photos which returns 'content://com.google.android'
_Some of them also suggests using DATA_URL on destination type but it is memory intensive and may cause the app to crash_
Here is my code:
TS file
selectImage(sourceType) {
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
saveToPhotoAlbum: true,
sourceType: sourceType
}
this.camera.getPicture(options).then((imageData) => {
let base64Image = 'data:image/jpeg;base64,' + imageData;
this.imagePreview = imageData;
}, (err) => {
this.toastCtrl.presentToast(err);
});
}
HTML File
<img src="{{imagePreview}}" />;
I hope someone could help me with this. Thank you in advance 💖.
ts:
public base64Image:string;
public getImage(){
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imageData) => {
this.base64Image = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
// Handle error
});
}
html:
<imge src={{base64Image}} />
Give this a try:-
//From Gallery
ChooseGallery() {
var _self=this;
const options: CameraOptions = {
allowEdit: true,
correctOrientation: true,
quality: 100, // picture quality
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
sourceType: this.camera.PictureSourceType.SAVEDPHOTOALBUM
}
this.camera.getPicture(options).then((ImageData) => {
_self.base64value = ImageData;
})
}
From Camera
ChooseCamera() {
var _self=this;
const options: CameraOptions = {
allowEdit: true,
correctOrientation: true,
quality: 100, // picture quality
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((ImageData) => {
_self.base64value = ImageData;
})
}
I hope this helps! Thanks!
Solved my problem using DomSanitizer https://devfanaticblog.com/working-with-camera-in-ionic-2-and-ionic-native/
let options: CameraOptions = {
quality: 100,
sourceType: this.camera.PictureSourceType.SAVEDPHOTOALBUM,
saveToPhotoAlbum: true,
correctOrientation: true,
encodingType: this.camera.EncodingType.JPEG,
destinationType: this.camera.DestinationType.FILE_URI
};
this.camera.getPicture(options).then((imageData) => {
let photo_split=imageData.split("%3A");
let photo_split2=photo_split[0].split("?");
let filename = photo_split2[0].substring(photo_split2[0].lastIndexOf('/')+1);
let path = photo_split2[0].substring(0,photo_split2[0].lastIndexOf('/')+1);
alert(photo_split2[0])
alert(filename)
alert(path)
this.file.readAsDataURL(path, filename).then(res=> {
alert("FUNCIONA!")
this.imageURI = res;
}).catch((reason) => {
alert(JSON.stringify(reason));
});
}).catch((reason) => {
alert(JSON.stringify(reason));
});
//HTML
<img alt="uploaded Image" [src]="imageURI">
How do you display a FILE_URI image taken by the user using #ionic-native/camera in Ionic 3?
I can use Ionic Native's Camera to get a FILE_URI image URL, with a result like this:
file:///var/mobile/Containers/Data/Application/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX/tmp/cdv_photo_005.jpg
However, When I try to display this image back to the user by referring to the URI in my view template, the image never loads.
Things I've tried:
-Using the image URI directly in the view
<img src="{{profile.image}}"> // Never loads
-Sanitizing the URI by including DomSanitizer in the page component:
<img [src]="domSanitizer.bypassSecurityTrustUrl(profile.image)"> // Never loads
I would rather not use a base64 image because of the performance drag. What am I doing wrong here?
import { normalizeURL } from 'ionic-angular'; ionic3 <img> tag src
<img *ngIf="base64Image" src="{{base64Image}}"/>
openCamera(pictureSourceType: any) {
let options: CameraOptions = {
quality: 95,
destinationType: this.camera.DestinationType.FILE_URI,
sourceType: pictureSourceType,
encodingType: this.camera.EncodingType.PNG,
targetWidth: 400,
targetHeight: 400,
saveToPhotoAlbum: true,
correctOrientation: true
};
this.camera.getPicture(options).then(imageData => {
if (this.platform.is('ios')) {
this.base64Image = normalizeURL(imageData);
// Alternatively if the problem only occurs in ios and normalizeURL
// doesn't work for you then you can also use:
// this.base64Image= imageData.replace(/^file:\/\//, '');
}
else {
this.base64Image= "data:image/jpeg;base64," + imageData;
}
}, error => {
console.log('ERROR -> ' + JSON.stringify(error));
});
}
Hi try to use File Path ionic plugin
path = "file:///var/mobile/Containers/Data/Application/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX/tmp/cdv_photo_005.jpg";
this.filePath.resolveNativePath(path)
.then(filePath => console.log(filePath))
.catch(err => console.log(err));
Please read the documentation
https://ionicframework.com/docs/native/file-path/
You can use the below code for display the image
savePhotoClick = () =>{
const options: CameraOptions = {
quality: 70,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64 (DATA_URL):
this.base64Image = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
// Handle error
});
Then use the img tag for display
<img [src]="base64Image" *ngIf="base64Image" />
My backen looks like this. The backend required a file and 2 string params
#multipart/form-data
file: File,
title: string,
content: string
I used to use to select file then upload it to server via httpClient and formData
const formData = new FormData();
formData.append('title', form.value.title);
formData.append('content', form.value.description);
formData.append('file', this.img);
this.http.post(this.apiUrl + '/img', formData, settings);
Everything works just fine.
But now I decide that I do not want to use any more. I decide to use native camera
getPictureFromCamera() {
return new Promise((resolve, reject) => {
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imageData) => {
let base64Image = null;
//get photo from the camera based on platform type
base64Image = normalizeURL(imageData);
resolve(base64Image);
}, (error) => {
console.debug("Unable to obtain picture: " + error, "app");
reject(error);
});
})
}
I successfully can take and display the picture. The problem is that my function only return the path of image (not the file). How can I get the actual file so I can use form-data and httpClient to post it to my server.
I want to use my old formdata function so I just need a file. Is there any way I just only get a file from imgPath.
Note: when I log 'base64Image' (you can see in the code above)
http://localhost:8080/var/mobile/Containers/Data/Application/85D7DD14-849C-4ADE-9005-D8165CC2A55B/tmp/cdv_photo_001.jpg
I am using IONIC 3.7.0 in my current project. In one requirement I need to use cordova camera plugin to take photo uri from image gallery. Every time when I am trying to get the URI , I get the data_uri which is base64 long string.
I only need the file_uri of image to go further. Please suggest.
var options = {
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
destinationType: Camera.DestinationType.FILE_URI
};
Camera.getPicture(options)
.then((imageData) => {
console.log(imageData);
this.fileToUpload = imageData;
const base64Image = "data:image/jpeg;base64," + imageData;
this.preloadImage._img.src = base64Image;
this.codeservice.doProfileImageUpload(base64Image)
.subscribe(res => {
if(res.length()>0){
console.log('updated');
}
})
}, (err) => {
console.log(err);
});