Ionic Native HTTP send a file using POST and multipart/form-data

Hi everyone!
I am trying to do a http post call using the Ionic Native Http plugin in order to send a file using a FormData, but it is not working as expected… I attach a piece of my simple code in typescript.

  1. First of all, I generate the formData and after that I call the service that triggers the http post call:

  2. Do the call using the Ionic Http Plugin with the multipart and the formData:
    Screenshot 2020-09-15 at 17.30.41

So, the problem that I am facing is that my code is not reaching the debugger inside the .then() method and I don’t know why… of course, neither in the .catch(), so no errors here…

On the another hand, if I delete the .setDataSerializer(‘multipart’) the http plugin displays the following error: "data" argument supports only following data types: Object, so it seems that when I am using the multipart that promise is not executed or is not ended. Has anyone had the same problem?

Thanks in advance for your support!

Did you found any solution for this…

The http return an Observable; is necessary to “sign up” with “subscribe”:

.then(...)
.catch(...)
.subscribe(next => {console.log(next)});

P.S.: is not an ionic native plugin but an angular native plugin.

Have you find any solution ??

Take a look here how i solved multipart/form-data using ionic native http

1 Like

I am getting your point

Did you manage to fix it?

In my case, I am using the a request as XMLHttpRequest, this is my final code:

private multipartPost(url: string, body: any, authToken: string): Promise<any>{
	return new Promise((resolve, reject) => {
		let request = new XMLHttpRequest();
		request.open('POST', url);
		request.setRequestHeader('Authorization', authToken);
		request.withCredentials = true;
		request.send(body);
		request.onreadystatechange = () => {
			if (request.readyState === 4) {
				if (request.status == 200) {
					return resolve(true);
				}
				else {
					return reject(false);
				}
			}
		};
	
		request.onerror = (e) => {
			return reject(e);
		};
	});
}

Why not just use Angular’s HttpClient, with which your entire multipartPost could be replaced by a single line of code, with the additional benefit of being able to easily and cleanly separate out and centralize the authorization handling, so that every HTTP request in your app can get it for free?

This work for me. Thanks.

The solution:

1.- this.http.setDataSerializer('multipart')
2.- Use: new cordova.plugin.http.ponyfills.FormData(); instead of new FormData();
3.- Example of headers:

{
  'enctype': 'multipart/form-data;',
  'Accept': 'plain/text',
  'Access-Control-Allow-Origin': '*',
}