Académique Documents
Professionnel Documents
Culture Documents
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.
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:
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.
We don’t need any special routing so our image upload app is prepared for some action!
UPDATE: The issue is closed, so you shouldn’t get into any trouble.
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.
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:
(http://ionicacademy.com/?
utm_source=devtut&utm_medium=ad2)
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 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.
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:
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.
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 }
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.
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!
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:
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:
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!
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.
First
Name
Email
Address
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.
48
Comments Devdactic
1 Login
Recommend 3 t Tweet f Share Sort
by
Best
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;
Nanda
thoomathy > Sumeet Chawla • 6 months ago • edited
handler:()=>{
}
use => instead of >
1△ ▽ • Reply • Share ›
Simon
Grimm Mod > Sumeet Chawla • 15 days ago
Ah dL i 2 th
Ahmad
Lazim • 2 months ago
how about upload multiple images ?
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)
Simon
Grimm Mod > Llorenç Vaquer • 14 days ago
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!
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 ›
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 ›
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 ›
Simon
Grimm Mod > GerryMaddox • 8 months ago
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 ›
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)
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/)
Thanks in advance
△ ▽ • 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)
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
18h
Simon Grimm
@schlimmson
FEATURED ON:
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.