Vous êtes sur la page 1sur 20

Devdactic

The Ionic 4 Images Guide (Capture, Store & Upload with


POST)
OCTOBER 2, 2018 BY SIMON (HTTPS://DEVDACTIC.COM/AUTHOR/SIMON-REIMLER/)

If your app is working with


images and you need to handle
both local files and upload files
things can get a bit tricky with
Ionic. Especially as debugging
the filesystem and paths is
cumbersome, it’s not
automatically clear how
everything needs to work.

This Ionic 4 images guide aims


to clarify how you can:

Capture images using camera or


photo library
Store image files inside your Ionic 4 app
Upload files from their local path using a POST request

The result will be a simple app like you can see below.

We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.

Ok Read more (https://devdactic.com/privacy-policy/)


For this tutorial I used the Ionic 4 beta so perhaps some details might slightly change over the next time!

Starting our Ionic 4 Image Upload App


To get started we create a blank new Ionic 4 app and install all the plugins we need. I used the beta version of the Ionic Native
plugins to get version 5.x which work best with our Ionic 4 app.

Of course we need the camera and file plugin, but we also need the new Webview package for a reason we will see later. For
now go ahead and run:

Start our Image Upload App


1 ionic start devdacticImages blank --type=angular
2 cd devdacticImages
3  
4 # Ionic Native Packages
5 npm i @ionic-native/camera@beta
6 npm i @ionic-native/file@beta
7 npm i @ionic-native/ionic-webview@beta
8 npm i @ionic-native/file-path@beta
9  
10 # Cordova Packages
11 ionic cordova plugin add cordova-plugin-camera
12 ionic cordova plugin add cordova-plugin-file
13 ionic cordova plugin add cordova-plugin-ionic-webview
14 ionic cordova plugin add cordova-sqlite-storage
15 ionic cordova plugin add cordova-plugin-filepath

Now we need to hook up everything inside our module so we can use the plugins later. We also make use of the Ionic Storage
not to store the files but the path to a le later on.

Go ahead and change your src/app/app.module.ts to:

Import everything to our app Module


1 import { NgModule } from '@angular/core';
2 importWe{ use cookies to ensure
BrowserModule that we
} from give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.
'@angular/platform-browser';
3 import { RouterModule, RouteReuseStrategy, Routes } from '@angular/router';
Ok Read more (https://devdactic.com/privacy-policy/)
4  
5 i { I i M d l I i R S } f '@i i / l '
5 import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
6 import { SplashScreen } from '@ionic-native/splash-screen/ngx';
7 import { StatusBar } from '@ionic-native/status-bar/ngx';
8  
9 import { AppComponent } from './app.component';
10 import { AppRoutingModule } from './app-routing.module';
11  
12 import { HttpClientModule } from '@angular/common/http';
13  
14 import { Camera } from '@ionic-native/Camera/ngx';
15 import { File } from '@ionic-native/File/ngx';
16 import { WebView } from '@ionic-native/ionic-webview/ngx';
17 import { FilePath } from '@ionic-native/file-path/ngx';
18  
19 import { IonicStorageModule } from '@ionic/storage';
20  
21 @NgModule({
22   declarations: [AppComponent],
23   entryComponents: [],
24   imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule,
25     HttpClientModule,
26     IonicStorageModule.forRoot()
27     ],
28   providers: [
29     StatusBar,
30     SplashScreen,
31     { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
32     Camera,
33     File,
34     WebView,
35     FilePath
36   ],
37   bootstrap: [AppComponent]
38 })
39 export class AppModule {}

We don’t need any special routing so our image upload app is prepared for some action!

Fix the WkWebView Plugin


At the time writing this tutorial there was also a bug within the webview plugin for iOS which leads to an app crash. You can
see the details in this issue (https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/133) which might already be
fixed later.

UPDATE: The issue is closed, so you shouldn’t get into any trouble.

If you still encounter problems, you can open your platforms/ios/devdacticImages/Plugins/cordova-plugin-ionic-


webview/CDVWKWebViewEngine.m and replace it with the contents of the fixed file (https://github.com/ionic-team/cordova-
plugin-ionic-webview/pull/135/files).

The View for Our Image Upload & Management App


Let’s start with the easiest part which is the view in our Ionic 4 image upload app. We need to display a button so users can
select am image to upload. This will trigger an action sheet, and once the user has finished the image dialog a new image will
be displayed inside the list.

The list itself shows all of our locally stored files (more on the logic later) with a button to upload the image and to delete the
file and all
Wereferences.
use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.

Ok Read more (https://devdactic.com/privacy-policy/)

There isn’t really much about this so first of all now change your src/app/home/home page html to this:
There isn t really much about this so first of all now change your src/app/home/home.page.html to this:

The view with our image slist and buttons


1 <ion-header>
2   <ion-toolbar color="primary">
3     <ion-title>
4       Ionic Image Upload
5     </ion-title>
6   </ion-toolbar>
7 </ion-header>
8  
9 <ion-content padding>
10   <h3 *ngIf="images.length == 0" text-center>Please Select Image!</h3>
11  
12   <ion-list>
13     <ion-item *ngFor="let img of images; index as pos" text-wrap>
14       <ion-thumbnail slot="start">
15         <ion-img [src]="img.path"></ion-img>
16       </ion-thumbnail>
17       <ion-label>
18         {{ img.name }}
19       </ion-label>
20       <ion-button slot="end" fill="clear" (click)="startUpload(img)">
21         <ion-icon slot="icon-only" name="cloud-upload"></ion-icon>
22       </ion-button>
23       <ion-button slot="end" fill="clear" (click)="deleteImage(img, pos)">
24         <ion-icon slot="icon-only" name="trash"></ion-icon>
25       </ion-button>
26     </ion-item>
27   </ion-list>
28 </ion-content>
29  
30 <ion-footer>
31   <ion-toolbar color="primary">
32     <ion-button fill="clear" expand="full" color="light" (click)="selectImage()">
33       <ion-icon slot="start" name="camera"></ion-icon>
34       Select Image</ion-button>
35   </ion-toolbar>
36 </ion-footer>

(http://ionicacademy.com/?
utm_source=devtut&utm_medium=ad2)

The Basics for Our Image Upload

Let’s dive into the real action. I’ll split the code for the class in multiple sections so we can go over them one by one. To start,
let’s add We
all use
thecookies
dependencies
to ensure thatour class
we give you needs (which are
the best experience quite
on our a few)
website. If youand thetofirst
continue function
use this that
site we will will that
assume be called oncewith
you are happy theit. app
starts. Ok Read more (https://devdactic.com/privacy-policy/)
In the beginning we will look inside our storage to see if we have any stored information about images already captured. This
array will only contain the name of a le like “1234.png”, so for each entry we need to resolve the name to the local path of our
app which we add to the object as filePath.

To display the image we need another path, and here we can make use of the webview.convertFileSr()
which resolves a le:// path to a path that the WebView understands. All of this information goes to the local array which our
previous view can then iterate.

Now make the first changes inside your src/app/home/home.page.ts to get started:

The basic imports and loading for stored images

1 import { Component, OnInit, ChangeDetectorRef } from '@angular/core';


2 import { Camera, CameraOptions, PictureSourceType } from '@ionic-native/Camera/ngx';
3 importWe{ use
ActionSheetController,
cookies to ensure that weToastController, Platform,
give you the best experience LoadingController
on our } from
website. If you continue '@ionic/angular';
to use this site we will assume that you are happy with it.
4 import { File, FileEntry } from '@ionic-native/File/ngx';
Ok Read more (https://devdactic.com/privacy-policy/)
5 import { HttpClient } from '@angular/common/http';
6 i t { W bVi } f '@i i ti /i i b i / '
6 import { WebView } from '@ionic-native/ionic-webview/ngx';
7 import { Storage } from '@ionic/storage';
8 import { FilePath } from '@ionic-native/file-path/ngx';
9  
10 import { finalize } from 'rxjs/operators';
11  
12 const STORAGE_KEY = 'my_images';
13  
14 @Component({
15   selector: 'app-home',
16   templateUrl: 'home.page.html',
17   styleUrls: ['home.page.scss'],
18 })
19 export class HomePage implements OnInit {
20  
21   images = [];
22  
23   constructor(private camera: Camera, private file: File, private http: HttpClient, private webview: WebView,
24     private actionSheetController: ActionSheetController, private toastController: ToastController,
25     private storage: Storage, private plt: Platform, private loadingController: LoadingController,
26     private ref: ChangeDetectorRef, private filePath: FilePath) { }
27  
28   ngOnInit() {
29     this.plt.ready().then(() => {
30       this.loadStoredImages();
31     });
32   }
33  
34   loadStoredImages() {
35     this.storage.get(STORAGE_KEY).then(images => {
36       if (images) {
37         let arr = JSON.parse(images);
38         this.images = [];
39         for (let img of arr) {
40           let filePath = this.file.dataDirectory + img;
41           let resPath = this.pathForImage(filePath);
42           this.images.push({ name: img, path: resPath, filePath: filePath });
43         }
44       }
45     });
46   }
47  
48   pathForImage(img) {
49     if (img === null) {
50       return '';
51     } else {
52       let converted = this.webview.convertFileSrc(img);
53       return converted;
54     }
55   }
56  
57   async presentToast(text) {
58     const toast = await this.toastController.create({
59         message: text,
60         position: 'bottom',
61         duration: 3000
62     });
63     toast.present();
64   }
65  
66   // Next functions follow here...
67  
68 }

Adding New Images

The next step is to add new images. We start this process by displaying an action sheet from which the user can either select
the camera or photo
We use library
cookies to ensure as
thatawesource.
give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.

Ok Read more (https://devdactic.com/privacy-policy/)

Once the source is defined we use the camera like always and we are not using a base64 as a result but the real FILE URI of
Once the source is defined we use the camera like always and we are not using a base64 as a result but the real FILE_URI of
the image. Otherwise we would have to store those super big strings inside the storage which is not really considered best
practice.

After the image was selected we want to copy the le over to our apps data directory with a new name so we are not more
dependent on where the file really exists as we have our own copy.

Go ahead and add the 2 functions below what you already got:

Select and capture new images


1 async selectImage() {
2     const actionSheet = await this.actionSheetController.create({
3         header: "Select Image source",
4         buttons: [{
5                 text: 'Load from Library',
6                 handler: () => {
7                     this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
8                 }
9             },
10             {
11                 text: 'Use Camera',
12                 handler: () => {
13                     this.takePicture(this.camera.PictureSourceType.CAMERA);
14                 }
15             },
16             {
17                 text: 'Cancel',
18                 role: 'cancel'
19             }
20         ]
21     });
22     await actionSheet.present();
23 }
24  
25 takePicture(sourceType: PictureSourceType) {
26     var options: CameraOptions = {
27         quality: 100,
28         sourceType: sourceType,
29         saveToPhotoAlbum: false,
30         correctOrientation: true
31     };
32  
33     this.camera.getPicture(options).then(imagePath => {
34         if (this.platform.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
35             this.filePath.resolveNativePath(imagePath)
36                 .then(filePath => {
37                     let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
38                     let currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1, imagePath.lastIndexOf('?'));
39                     this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
40                 });
41         } else {
42             var currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
43             var correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
44             this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
45         }
46     });
47  
48 }

Copy Files & Store Local Reference

So we got the image file and want to copy it to our app. For the copy function we need the path to the original file, the name,
the new path
We useand thetonew
cookies name.
ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.

Ok Read more (https://devdactic.com/privacy-policy/)

This function will then copy over the original file under the new name to our data directory
This function will then copy over the original file under the new name to our data directory.

Now it’s not really a good idea to list only the files inside our app to keep track of them, as you might perhaps also need to
store additional information.

Therefore, we update our Storage and store the information with the JSON.stringify() as an array back. Also, we create one
additional object that we add to our local array with the according information and resolved paths like we also do when our app
starts.

Here’s the logic to copy the file and store the information:

The logic for copying files to our app folder and storing a reference
1 createFileName() {
2     var d = new Date(),
3         n = d.getTime(),
4         newFileName = n + ".jpg";
5     return newFileName;
6 }
7  
8 copyFileToLocalDir(namePath, currentName, newFileName) {
9     this.file.copyFile(namePath, currentName, this.file.dataDirectory, newFileName).then(success => {
10         this.updateStoredImages(newFileName);
11     }, error => {
12         this.presentToast('Error while storing file.');
13     });
14 }
15  
16 updateStoredImages(name) {
17     this.storage.get(STORAGE_KEY).then(images => {
18         let arr = JSON.parse(images);
19         if (!arr) {
20             let newImages = [name];
21             this.storage.set(STORAGE_KEY, JSON.stringify(newImages));
22         } else {
23             arr.push(name);
24             this.storage.set(STORAGE_KEY, JSON.stringify(arr));
25         }
26  
27         let filePath = this.file.dataDirectory + name;
28         let resPath = this.pathForImage(filePath);
29  
30         let newEntry = {
31             name: name,
32             path: resPath,
33             filePath: filePath
34         };
35  
36         this.images = [newEntry, ...this.images];
37         this.ref.detectChanges(); // trigger change detection cycle
38     });
39 }

Delete Local Files


We got almost all important parts in place, but if we want to finish this example we also need the delete function. At this point
you need to take care of 3 elements:

Remove the object from our local images array


Remove the item from the Ionic Storage
Remove the actual file from our app folder
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.
But don’t worry, all of those actions can be performed
Ok with(https://devdactic.com/privacy-policy/)
Read more just one simple function:
Delete one image from the filesystem
1 deleteImage(imgEntry, position) {
2     this.images.splice(position, 1);
3  
4     this.storage.get(STORAGE_KEY).then(images => {
5         let arr = JSON.parse(images);
6         let filtered = arr.filter(name => name != imgEntry.name);
7         this.storage.set(STORAGE_KEY, JSON.stringify(filtered));
8  
9         var correctPath = imgEntry.filePath.substr(0, imgEntry.filePath.lastIndexOf('/') + 1);
10  
11         this.file.removeFile(correctPath, imgEntry.name).then(res => {
12             this.presentToast('File removed.');
13         });
14     });
15 }

Upload Files with POST and Form Data


We got files, we got the storage, we got all information we need but still the upload process for files isn’t that easy. In our
example we will have a PHP backend that accepts our file (we’ll build it in the last step) and we need to post it somehow. Also,
we don’t need to use the old file transfer plugin anymore, all of this also works with the general POST of Angular HTTP.

Some of the following logic for reading the local file comes from this great tutorial (https://golb.hplar.ch/2017/02/Uploading-
pictures-from-Ionic-2-to-Spring-Boot.html).

The idea is that we first need to resolve the path of our local file which results in a FileEntry object. On this object we can
than call the file() function and use a FileReader to read in the data of a file object.

The result is a blob the we can add as FormData to our request which is in the end a standard HTTP POST call with the form
data.

Now go ahead and add the last functions to your class:

Logic for uploading our local image files

1 // Inspired by https://golb.hplar.ch/2017/02/Uploading-pictures-from-Ionic-2-to-Spring-Boot.html (https://golb.hplar.ch/2017/02/Uploadin


2  
3 startUpload(imgEntry) {
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.
4     this.file.resolveLocalFilesystemUrl(imgEntry.filePath)
Ok Read more (https://devdactic.com/privacy-policy/)
5         .then(entry => {
6 ( Fil E t t ) fil (fil thi dFil (fil ))
6             ( < FileEntry > entry).file(file => this.readFile(file))
7         })
8         .catch(err => {
9             this.presentToast('Error while reading file.');
10         });
11 }
12  
13 readFile(file: any) {
14     const reader = new FileReader();
15     reader.onloadend = () => {
16         const formData = new FormData();
17         const imgBlob = new Blob([reader.result], {
18             type: file.type
19         });
20         formData.append('file', imgBlob, file.name);
21         this.uploadImageData(formData);
22     };
23     reader.readAsArrayBuffer(file);
24 }
25  
26 async uploadImageData(formData: FormData) {
27     const loading = await this.loadingController.create({
28         content: 'Uploading image...',
29     });
30     await loading.present();
31  
32     this.http.post("http://localhost:8888/upload.php (http://localhost:8888/upload.php)", formData)
33         .pipe(
34             finalize(() => {
35                 loading.dismiss();
36             })
37         )
38         .subscribe(res => {
39             if (res['success']) {
40                 this.presentToast('File upload complete.')
41             } else {
42                 this.presentToast('File upload failed.')
43             }
44         });
45 }

That’s all for the Ionic image upload app, the app will work now besides the upload part but you can run it already now.

Make sure that you are running the app on the simulator/device as we use the camera and filesystem so it will only work
where Cordova is available!

The PHP Upload Logic


Now I’m not a PHP expert so I’ll make this as quick as possible.

If you have a server you can use that one, otherwise I simply recommend to download XAMPP
(https://www.apachefriends.org/de/index.html) and install it local.

I’m not going to cover that process since this is about Ionic image upload and not how to configure PHP. If you have set it up,
you can first of all create a upload.php to accept uploads:

The upload.php to accept new images

1 <?php
2 header('Access-Control-Allow-Origin: *');
3 $target_path = "uploads/";
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.
4
Ok Read more (https://devdactic.com/privacy-policy/)
5 $target_path = $target_path . basename( $_FILES['file']['name']);
6
6
7 if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
8     header('Content-type: application/json');
9     $data = ['success' => true, 'message' => 'Upload and move success'];
10     echo json_encode( $data );
11 } else{
12     header('Content-type: application/json');
13     $data = ['success' => false, 'message' => 'There was an error uploading the file, please try again!'];
14     echo json_encode( $data );
15 }
16  
17 ?>

Also, make sure to create a uploads folder next to this file, as it will copy the images into that folder.

Additionally, to see the results of our hard work, I created a little HTML file that will scan the uploads folder and show them so
we can directly see if our upload worked, create this as index.php next to the previous file and insert:

A simple view for our images


1 <!DOCTYPE html>
2 <html>
3 <head>
4   <meta charset="utf-8">
5   <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
6   <title>Devdactic Image Upload</title>
7 </head>
8 <body>
9 <h1>Ionic Image Upload</h1>
10   <?php
11   $scan = scandir('uploads');
12   foreach($scan as $file)
13   {
14     if (!is_dir($file))
15     {
16         echo '<h3>'.$file.'</h3>';
17       echo '<img src="uploads/'.$file.'" style="width: 400px;"/><br />';
18     }
19   }
20   ?>
21 </body>
22 </html>

You can now start your local MAMP server and navigate to http://localhost:8888 (http://localhost:8888) which will display your
Ionic Images overview.

In our example we used this URL for the upload, but this will only work if you run the app on the simulator. If you deploy the app
to your iOS device you need to change the URL to the IP of your computer!

Conclusion
The process of capturing image with Ionic 4 is still the same, but storing local files and uploading works actually a bit easier
then with previous versions.

If you don’t see your files it’s most likely an issue with the WKWebView and how local files can be displayed, so if you
encounter any problems please provide some further logs!

You can also find a video version of this article below.

We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.

Ok Read more (https://devdactic.com/privacy-policy/)


(http://ionicacademy.com/?
utm_source=devtut&utm_medium=ad3)

The Ionic 4 Images Guide (Capture, Store & Upload w…


w…

First
Name
Email
Address

Powered by ConvertKit (http://mbsy.co/convertkit/23139740)

Get the free


7
day
Ionic
4
Crash
Course to learn how to:

Get started with Ionic


Build a Tab Bar navigation
Make HTTP calls to a REST API
Store Data inside your app
Use Cordova plugins
Style your Ionic app

The
course
is
free, so there's nothing you can lose!

We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.

Ok Read more (https://devdactic.com/privacy-policy/)


About Simon
Ionic Framework Expert • Educator, Consultant & Speaker • Creator of the Ionic Academy

48
Comments Devdactic 
1 Login


Recommend 3 t Tweet f Share Sort
by
Best

Join the discussion…

LOG
IN
WITH OR
SIGN
UP
WITH
DISQUS ?

Name

Jameesh
Moidunny • 6 months ago
Hi I am getting null array in php $_FILES, please any one can help me
7△ ▽ • Reply • Share ›

Gonçalo
Forte • 9 months ago
I'm using Ionic's DevApp to test this in Android and when I tap the button "Select
Image" and then "Use Camera", nothing happens. Is there any way to debug this
(see the logs) on my Android?
5△ ▽ • Reply • Share ›

Christian
Blanco > Gonçalo Forte • 6 months ago
Bro, You can use the app debugger which is integrated in Chrome, you can
type Ctrl+Shift+i and in the window that opened you can click on the 3 dots
button, then you go to "more tools" and there you will find a menu called
"remote devices" then you start a debug for your device and in the console
you will see all the logs.
△ ▽ • Reply • Share ›

Sumeet
Chawla • 7 months ago
Correction:

In the method selectImage, the > operator got converted & gt;

handler: () = & gt;


2△ ▽ • Reply • Share ›

Nanda
thoomathy > Sumeet Chawla • 6 months ago • edited
handler:()=>{
}
use => instead of >
1△ ▽ • Reply • Share ›

Simon
Grimm Mod > Sumeet Chawla • 15 days ago

Thanks, it is fixed now!


We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.
△ ▽ • Reply • Share ›
Ok Read more (https://devdactic.com/privacy-policy/)

Ah dL i 2 th
Ahmad
Lazim • 2 months ago
how about upload multiple images ?
1△ ▽ • Reply • Share ›

Cormac • 3 months ago


Hi I seem to get either a File upload failed, or else the loader just keeps spinning!
Any ideas?
1△ ▽ • Reply • Share ›

Nur
Khasanah • 6 months ago
bro someone know how to upload multiple image using this method ?
1△ ▽ • Reply • Share ›

Hamzah
Alvana • 5 days ago
Hi, maybe anyone can help me how to save picture into specific directory location?
I am getting stuck how to using the native file method. :(
△ ▽ • Reply • Share ›

Simon
Grimm Mod > Hamzah Alvana • 3 hours ago

You need to make sure the folder exists, so if it doesn't yet you can create a
folder with the file plugin as well!
△ ▽ • Reply • Share ›

Simon
Gil • 24 days ago
Hi Simon and community, I want to automatically upload the photo once selected. I
am trying to use startUpload (imgEntry); inside the takePicture. Please help...

takePicture(sourceType: PictureSourceType) {
var options: CameraOptions = {
quality: 100,
sourceType: sourceType,
saveToPhotoAlbum: false,
correctOrientation: true
};
this.camera.getPicture(options).then(imagePath => {
if (this.plt.is('android') && sourceType ===
this.camera.PictureSourceType.PHOTOLIBRARY) {
this.filePath.resolveNativePath(imagePath)

.then(filePath => {
let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
let currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1,
imagePath.lastIndexOf('?'));
this.copyFileToLocalDir(correctPath, currentName, this.createFileName());

setTimeout((imgEntry) => {
this.startUpload(imgEntry);
//HERE
}, 1000);

});
△ ▽ • Reply • Share ›

Simon
Grimm Mod > Simon Gil • 14 days ago

What's exactly not working? Is your startUpload not called? Just make sure
it's in the then() block of all the operations before, but then it shouldn't be a
problem to directly upload it if all previous operations are finished!
△ ▽ • Reply • Share ›

Llorenç
Vaquer • 24 days ago
Hello Simon! First, thank you for this great tutorial.

I'm
Wehaving a problem
use cookies to that
to ensure upload a file
we give youimage using
the best your code
experience on ourtowebsite.
uploadIfanyouimage
continue to use this site we will assume that you are happy with it.
with FormData using the devices iOS and Android. The difference between your
Ok Read more (https://devdactic.com/privacy-policy/)
code and mine is that I'm using interceptors. Could this be my problem? The server
response is OK, but the image is not uploaded. (Server app is 3rd party)

Thank you in advance


△ ▽ • Reply • Share ›

Simon
Grimm Mod > Llorenç Vaquer • 14 days ago

Hmm actually I don't think the interceptor will be a problem if it doesn't


change or remove the formData! Maybe check on your server side in the
request if there's an image coming through!
△ ▽ • Reply • Share ›

Pieter-Jan
Van
de
Perre • a month ago
I'm going to post here because I had been struggling with this for two weeks.
If your server gives you an error message that the file upload didn't work but for no
apparent reason, check if you have any HttpInterceptors in your project. I just
commented them out and saw the file upload work like a charm... I'm now going to
find out why exactly that happens.
△ ▽ • Reply • Share ›

Pieter-Jan
Van
de
Perre • a month ago
Hello,

In the conclusion of your article, you state that if the files can't be seen it is most
likely a problem with WKWebView.
I have just that problem. Several things I've tried but without success. The code
fails on the line "this.webview.convertFileSrc(img);". Writing your own function that
excludes the "file://" prefix does not appear to solve anything.

The exact problem is that the chosen image (be it from the photo gallery or
generated by the camera) does not appear in the preview list:


see
more

△ ▽ • Reply • Share ›

shraddha
k • 2 months ago • edited
getting ERROR TypeError: Cannot read property 'path' of null when images are
loading for upload plz someone simon can u plz reply asap
△ ▽ • Reply • Share ›

Adrián
Steinsleger • 2 months ago
Hi there! Do any of you guys know how to obtain window.WEBVIEW_SERVER_URL
from webView, to use it in a specific class?
I've been trying several workarounds but I can't make convertFileSrc return nothing
but emptiness :(
△ ▽ • Reply • Share ›

Adrián
Steinsleger > Adrián Steinsleger • 2 months ago
nobody?
△ ▽ • Reply • Share ›

Travis
Bradfield • 2 months ago
Hello! This is a great tutorial. I've managed to implement successfully on Android.
When I run the same project on my iPhone I get a 500 error uploading an image
from thecookies
We use camerato.ensure
Photothat
library upload
we give works
you the best perfectly.
experience Camera upload
on our website. doesn't.
If you continue to use this site we will assume that you are happy with it.
△ ▽ • Reply • Share › Ok Read more (https://devdactic.com/privacy-policy/)
geethika • 3 months ago
Hi, I need to store a pdf or image file in SQLite i.e in the app storage and should
open within app. I will get the file from another database like MongoDB in the URL
format. Could anyone of you help me out of this and suggest any references to
complete the app storage using SQLite. or how to open url present in sqlite?
△ ▽ • Reply • Share ›

Piotr
Dusiński • 3 months ago • edited
Please tell is it possible to download this project?
Thank you!

I have many bugs:

ERROR in src/app/home/home.page.ts(101,18): error TS2339: Property 'platform'


does not exist
on type 'HomePage'.
src/app/home/home.page.ts(102,18): error TS2339: Property 'filePath' does not
exist on type 'HomePage'.src/app/home/home.page.ts(201,7): error TS2345:
Argument of type '{ content: string; }' is not assignable to parameter of type
'LoadingOptions'. Object literal may only specify known properties, and 'content'
does not exist in type 'LoadingOptions'.
[ERROR] An error occurred while running subprocess ng.
△ ▽ • Reply • Share ›

Moises
Serrano > Piotr Dusiński • 3 months ago
change content to message
1△ ▽ • Reply • Share ›

Alan
Hugo > Moises Serrano • a month ago
thanks!
△ ▽ • Reply • Share ›

Victor
Espina > Piotr Dusiński • 2 months ago
Change the reference to this.platform for this.plt.
△ ▽ • Reply • Share ›

Nicola
Coolshop • 4 months ago
Hi! I have a problem, in some android devices the upload not works. in my backend
php in variable $_FILES i see the image but has size 0. It has only just the name.
△ ▽ • Reply • Share ›

HeSawHerDead • 4 months ago


Can you please tell me how do i generate random images from firebase ? i want the
user to get new random images from the cloud firestore each time he opens the
app
△ ▽ • Reply • Share ›

Ka2984 • 4 months ago • edited


Great tutorial, does this work for PWA apps accessed on a mobile?
△ ▽ • Reply • Share ›

Ahmad
Hussian13 • 4 months ago
After I choose a picture it doesn't show up in the app, in what line do we assign the
picture ?
△ ▽ • Reply • Share ›

muhammad_48806 • 6 months ago


I am trying to make this code works with uploading videos but after i select the
target video it doesn't appear on the list. Any help with this??
△ ▽ • Reply • Share ›
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.
Mastershort • 6 months ago
Ok Read more (https://devdactic.com/privacy-policy/)
I used your code. But i got a problem
pathForImage(img) {
if (img === null) {
return '';
} else {

let converted = this.webview.convertFileSrc(img);


return converted;
}
}
i dont got everything back from converted
If use this.presentToast(img); before let converted =
this.webview.convertFileSrc(img);
i got the file:///..... back.

But if i use this.presentToast(converted); after let converted =


this.webview.convertFileSrc(img);
i got nothing

What can be the problem?


△ ▽ • Reply • Share ›

Ander
Mjz
Crr • 6 months ago
That was great! It works perfectly!
△ ▽ • Reply • Share ›

Ankit
Maheshwari • 7 months ago
I'm getting error!
Cannot read property 'path' of null

△ ▽ • Reply • Share ›

mohamed
ali • 8 months ago
i got problem with jSON.pars in loadStoredImages()
△ ▽ • Reply • Share ›

GerryMaddox • 8 months ago


Having trouble finding the property ImagePath in the take Picture function

if (this.plt.is('android') && sourceType ===


this.camera.PictureSourceType.PHOTOLIBRARY) {
this.filePath.resolveNativePath(imagePath)
△ ▽ • Reply • Share ›

GerryMaddox > GerryMaddox • 8 months ago


We usethis.filePath.resolveNativePath(imagePath)
cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.
image path is not a variable in this function.
Ok
Trying to figure out what you
Read more (https://devdactic.com/privacy-policy/)
actually meant,
△ ▽ • Reply • Share ›

Simon
Grimm Mod > GerryMaddox • 8 months ago

Sorry there was an indentation problem, updated the code yesterday


to include special handling for Android library! Now everything
should be correct again!
△ ▽ • Reply • Share ›

john
king > Simon Grimm • 8 months ago • edited
Thanks for your great tutorial, just what I was looking for.
To get the Android photolibrary working I had to add filepath
to the project.
Import it in the constructor:
private filePath: FilePath
And add to app.module.ts providers
Then rename the other variable called filePath to something
else.
Now it is working well.
△ ▽ • Reply • Share ›

gopal
venu • a year ago
i have followed your tutorial and getting this error..
ERROR in src/app/home/home.page.ts(178,7): error TS2345: Argument of type '{
content: string; }' is not assignable to parameter of type 'LoadingOptions'.
[ng] Object literal may only specify known properties, and 'content' does not exist
in type 'LoadingOptions'.
△ ▽ • Reply • Share ›

Gonçalo
Forte > gopal venu • 9 months ago
Use 'message' property instead of 'content'
2△ ▽ • Reply • Share ›

Mastech • a year ago


Hey Simon. This article was great, ordered code like a expert. I took as reference.
Im using firebase for my android app. Just asking if you are facing problem with
camera native plugin for android like this: https://github.com/apache/c... (After take
a picture, app is restarting). Really appreciate if you can give me a hand. Regards!
△ ▽ • Reply • Share ›

wamdeen • a year ago


Just what I was always looking for: ionic with php backend!. Thanks Simon
△ ▽ • Reply • Share ›

ToGlory • a year ago


Thanks !!!
△ ▽ • Reply • Share ›

Bibhu
padhy • a year ago
can you suggest me how to make a similar app using firebase, i doing a project
using firebase
△ ▽ • Reply • Share ›

Chege
Douglas • 3 months ago • edited
nice tutorial Simon one issue when you quit the app and launch it again the app
seems not to load the images also when we delete the photos and go to the cache
folder the images are still there (Android)

============ SOLVED ==============

I was able to solve this if anyone has this issue you can contact me i will get back
to you with a solution
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.
△ ▽ • Reply • Share ›
Ok Read more (https://devdactic.com/privacy-policy/)

DinocoM • 8 months ago


DinocoM • 8 months ago
Hello, may you help me with this error?

Property 'copyFileToLocalDir' does not exist on type 'HomePage'

Thanks in advance
△ ▽ • Reply • Share ›

DinocoM > DinocoM • 8 months ago


My mistake, I had a bad name definition for that function.

Thank you for this great turorial


△ ▽ • Reply • Share ›

ALSO
ON
DEVDACTIC

10
Tools
&
Services
Every
Ionic How
to
Build
an
Ionic
4
Calendar
App
Developer
Should
Know 4 comments • 6 months ago
3 comments • 7 months ago Hiren
Sharma — hii sir, i use this code
Muh_Sobari — Very Very Thanks Sir Avatarperfectly but is project not run in ipad
AvatarSimon 10.3.3 can you solve this problem some

How
to
Build
an
Ionic
4
App
with How
to
Create
a
Simple
Ionic
4
App
Offline
Mode with
Firebase
and
AngularFire
21 comments • a year ago 26 comments • a year ago
Sumeet
Chawla — Yup, thank you for John
Calhoun — Seems like you need to
Avatarsharing this. Avatarunsubscribe using the ngOnDestroy()

FOLLOW ME ON TWITTER

First
Name
Email
Address
Powered by ConvertKit

(http://mbsy.co/convertkit/23139740)

Get the free


7
day
Ionic
4
Crash
Course to learn how to:

Get started with Ionic

Build a Tab Bar navigation

Make HTTP calls to a REST API

Store Data inside your app

Use Cordova plugins

We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.
Style your Ionic app
Ok Read more (https://devdactic.com/privacy-policy/)
The
course
is
free, so there's
nothing you can lose! Tweets by @schlimmson
Simon Grimm
@schlimmson

What is a popular mobile app (or type of app) that


you would like to see built with @Ionicframework ?

18h

Simon Grimm
@schlimmson

Look who’s working on what the community wanted


him to work on

Feels really good to know that I’m working on the


right content that people actually need help with

And because I finished all tasks early (and a bit of


tomorrow’s work) I… ift.tt/2IcyzQE

Embed View on Twitter

FEATURED ON:

Copyright © 2019 · Devdactic

We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.

Ok Read more (https://devdactic.com/privacy-policy/)

Vous aimerez peut-être aussi