How to upload file using post method in ionic


#1

For picking file i am using following line.
<input type=“file” (change)=“changeListener($event)” />

please tell me the solution


#2

The solution is entirely dependent on what your server is expecting.


#3

Pasting all my code here is not good I guess. I recommend you read the docs below:

  1. take a picture
    https://ionicframework.com/docs/native/camera/

  2. upload the picture
    https://ionicframework.com/docs/native/file/
    https://ionicframework.com/docs/native/file-transfer/

If you are really taking a picture and upload it, you may need the file plugin to move the picture to a app directory before uploading it to the server.

However you can also try the method here:
http://blog.ionic.io/10-minutes-with-ionic-2-using-the-camera-with-ionic-native/

You can encode you file to a base64 string then post it like normal form data, or json.


#4

all parameter required by server is correct except one …which is ‘file’ parameter and it containes file …
so i am facing problem while passing file in ‘file’ parameter…so please tell me solution …
when i am using postman and selects file in ‘file’ parameter its working fine and uploading file.


#5

this solution is using upload method from native file-transfer;
But i want to use simple http post method to upload file And i am using browser’s file picker to pic file
<input type=“file” (change)=“changeListener($event)” />


#6

If so, I guess you can add a ‘name’ attribute to the file input(suppose the field name is “file”), like:
replace:

<input type=“file” (change)=“changeListener($event)” />

with:

<input type=“file” name="file"  (change)=“changeListener($event)” />

#7

What does that do?
What is the code?


#8

i have created that function and it will call that function after file selection


#9

Obviously…

But how are you trying to upload? Are you using IOnic Native File transfer? Or Angular’s http.post?


#10

i am using angular http post.
and i want to upload file using http post method


#11

Show us the code you have.


#12

@Rakesh21 Did you find the solution?

I am having the same problem: How to upload a file along with form data using http.post


#13

This might help : I have used nodejs and mongodb at backend

HTML::
<input type=“file” name=“image” accept=“image/*” (change)=“changeListener($event)”>

.ts
file: File;
changeListener($event): void {
this.file = $event.target.files[0];
this.imagesProvider.test1(this.file) // Calls test1() function in imagesProvider.ts
}

imagesProvider.ts:

test1(data){
var options = {
};
let body = new FormData();
body.append(‘image’, data);
body.append(‘desc’, “testing”);
this.http.post(“Your api endpoint”, body, options).subscribe(res => {
console.log(res);
});
;
}


#14

I tired it … it is working as you have used , but this will not work if we use ionic native camera or PHOTOLIBRARY