Upload file in ionic3


#1

Hello,
I have upload files in ionic3 … I don’t have use filetransfer but I use servie http post …

code ts:

if(this.images.length >0){
			  
			 loader.present(); 
			      for(var x=0;x<=this.images.length-1;x++)
			     {
			         if (this.images[x] !== "K" && this.images[x] !== "O") {
			this.images[x] = 'data:image/jpeg;base64,'+this.images[x];
			 this.http.post('https://b7e892c1.ngrok.io/wetry-api/web/upload',this.images[x], { headers: new HttpHeaders({'Content-Type': 'multipart/form-data'}) }).map(res =>

			 alert(res),
			        err => {
			          this.presentToast(err);
			        });

			}
			}
			}

with this code I don’t send file from ionic to serveur …

in this code I use formData but also error I don’t send file:

			const frmData = new FormData();
			     for(var x=0;x<=this.images.length-1;x++)
			     {
			         if (this.images[x] !== "K" && this.images[x] !== "O") {
			this.images[x] = 'data:image/jpeg;base64,'+this.images[x];
			alert(this.images[x]);
			      frmData.append("fileUpload", this.images[x]);
			      }
			      }
			alert('end append frmData');
			 this.http.post('https://b7e892c1.ngrok.io/wetry-api/web/upload',frmData, { headers: new HttpHeaders({'Content-Type': 'multipart/form-data'}) }).map(res =>

			 alert(res),
			        err => {
			          this.presentToast(err);
			        });

how to send file wih http post in ionic3 ?!


#2

As far as I know you need to use filetrasfer plugin of ionic.

Once the filetransfer is done successfully you can call the Http post method for may be database related stuffs.


#3

You haven’t told us the format your server is expecting. Usually with form submit you send the images as binary data not base 64 strings, but it’s impossible to know that without knowing your server.

You are correct in not using the file transfer plugin, it should not be used any longer, it has been deprecated.

I have a tutorial that could help you, but idk for sure since idk what your server wants. http://roblouie.com/article/574/learn-ionic-cordova-file-upload/


#4

code html is :slight_smile:

<ion-content padding>
 <button ion-button (click)="getPictures()">Get Pictures</button>
 <img src="{{imageFileName}}">
 <div *ngFor="let image of images">
 <img src="{{image}}"/>
 </div>
  <button ion-button (click)="uploadFile()">Upload File</button>
</ion-content>

I use php in code server and in code ts i convert image to base64

this is new code but also error any thing is send:

if(this.images.length >0){
  
 loader.present(); 
 const formData = new FormData();

      for(var x=0;x<=this.images.length-1;x++)
     {
         if (this.images[x] !== "K" && this.images[x] !== "O") {
this.images[x] = 'data:image/jpeg;base64,'+this.images[x];
formData.append('photos', this.images[x]);
}
}
 this.http.post('https://b7e892c1.ngrok.io/wetry-api/web/upload',formData, { headers: new HttpHeaders({'Content-Type': 'multipart/form-data'}) }).map(res =>

 alert(res),
        err => {
          this.presentToast(err);
        });
}

#5

Your server being php had nothing to do with the data format it expects


#6

okey but what is the solution ??


#7

I try coding with input file but in smartphone android I don’t select multiple file …
this is code html but i don’t select multiple files

 <input type="file" multiple #mulupload (change)="getPictures($event)" placeholder="upload a from web file"/>


#8

Did that work? Like besides not being able to select multiple files, did that actually post to your server?


#9

post in serveur is work but select multiple is not working with this code:

 <input type="file" multiple #mulupload (change)="getPictures($event)" placeholder="upload a from web file"/>


#10

Okay, that’s a good start. Now, we need to know what’s actually happening with this, can you:

  1. Show any code from the getPictures() method
  2. Show any code that accesses #mulupoad
  3. When you actually upload the file and it works, using Chrome debug tools go to the Network tab, find the actual POST request in the list of requests, click on it, and show us the ‘Request Payload’ section. If you can do that…we should be able to actually determine the data format your server expects…since…you still haven’t just told us. The section I’m looking for looks like this.


#11

code getPictures(event):

    getPictures(event){ 
      this.files= event.target.files;

code upload file:

testup()
{
 console.log(this.files);
for(var s=0;s< this.files.length;s++)
{
  //var x = 'data:image/jpeg;base64,'+ this.files[s].name;
  //formData.append('photo',this.files[s]);
  this.imgarr.push(this.files[s]);
}

for(var x of this.imgarr)
{
  if(x!== 'K' && x!=='O')
  {

  var formData = new FormData();
  formData.append('photo',x);

   this.http.post('https://f286cdea.ngrok.io/wetry-api/web/upload',formData, {responseType: 'text'}).subscribe(res =>

 alert(res),
        err => {
          this.presentToast(err);
        });
   
  }

  }
}

code html:

<ion-content padding>
 <input type="file" multiple #mulupload (change)="getPictures($event)" placeholder="upload a from web file"/>

  <button ion-button (click)="testup(); mulupload.value=''" >test Up</button>
</ion-content>

when i check with network return response object File …


#12

@rlouie

Chrome Debug (Network):

qqq


#13

Perfect. So, just as I thought, your server is expecting the binary file data, which you properly send in your web code. But then in your cordova code you are sending strings…so…it doesn’t work.

Luckily my blog post I posted earlier in this thread does literally exactly what you want so you can just follow that and you’ll have it working. The only difference is that my server expects it to be named ‘photos’ (plural), while yours expects ‘photo’ singular, and I send the filename to my server and you don’t.

Your code:
formData.append('photo',x);

Mine:
formData.append('photos', imageFile, imageFile.name);

So, just follow my blog post all the way through, but anywhere you see formData.append, send it ‘photo’ instead of ‘photos’ and don’t send the file name along. Otherwise it will work perfectly.


#14

@rlouie
I have this response

When I use this code:

testfile(){

  for (var l of this.images)
  {
    if(l !== 'K' && l !== 'O')
    {
     alert(l);
    var formData = new FormData();
  formData.append('photo',l);

   this.http.post('https://982ca091.ngrok.io/wetry-api/web/upload',formData, {responseType: 'text'}).subscribe(res =>

 alert(res),
        err => {
          this.presentToast(err);
        });
  }
}
}

code upload file:

  getImage(){
    this.imagePicker.getPictures({maximumImagesCount:10}).then( (results) => {
    for (var i = 0; i < results.length; i++) {
        this.images.push(results[i]);
    }
    }, (err) => {
      this.presentToast(err);
    });
  }

I use imagepicker plugin before i didn’t select multiple fil with in android


#15

Hi, I use this method

Ionic Code…


public sendImage(base64Image: string){
let fd:FormData = new FormData();
fd.append(‘photo’, base64Image);
//URL post
var service_url =this.urlpath+‘processImage’;
return this.http.post(service_url,fd);
}


Java code

Pay attention to “FormDataParam” have the same name in your server and ionic post code!!!

Check you code in server

fd.append(‘photo’, base64Image); = > @FormDataParam(“photo”) String photo


@POST
@Path("/processImage")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
//@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response processImage(@Context HttpHeaders httpHeaders,
@FormDataParam(“photo”) String photo) throws IOException{
//photo is a String B64, yo need decode an save
return Response.status(Response.Status.OK).
entity(responseObj(true,“My message”)).
header(“Access-Control-Allow-Origin”, “*”).build();

}


#16

Filetransfer plugin is now deprecated.

See here: https://github.com/apache/cordova-plugin-file-transfer#deprecated
and here: https://cordova.apache.org/blog/2017/10/18/from-filetransfer-to-xhr2.html

If someone needs an example of how to upload using formData and Http requests, this blog post may help you:
https://golb.hplar.ch/2017/02/Uploading-pictures-from-Ionic-2-to-Spring-Boot.html