I wanted to use only ionic plugin https://github.com/silkimen/cordova-plugin-advanced-http#uploadFile when uploading an camera/image file from device to API using the following methods.
While, it does not have any syntax error based on the documentation commented below.
The issue was related on the params, which I could not figure out why...
Error: advanced-http: "params" option needs to be an dictionary style object,
Method for uploading image to api.
async uploadToAPI(imgEntry) {
var url = environment.api_host + "/activities/log/images"
var filePath = imgEntry.localURL;
var name = 'reports';
var body = {
user_hash: 'xxxxxxx',
activities_id: 1,
activities_log_id: 1
}
var headers = {
'Authorization': 'Bearer ' + environment.api_security_bearer
}
// (method) HTTP.uploadFile(url: string, body: any, headers: any, filePath: string | string[], name: string | string[]): Promise<any>
// @param url — The url to send the request to
// @param body — The body of the request
// @param headers — The headers to set for this request
// @param filePath — The local path(s) of the file(s) to upload
// @param name — The name(s) of the parameter to pass the file(s) along as
// @returns — returns a FileEntry promise that will resolve on success, and reject on failure
this.http.uploadFile(
url,
body,
headers,
filePath,
name,
).then((data) => {
console.log(data)
})
.catch(error => {
console.log(error)
})
}
What could I be missing as a mistake on the following code above?
PS: Only, wanted to use the ionic-native/http/ngx and nothing else.
import { HTTP } from '@ionic-native/http/ngx';
I reported to the github repo from the original author, but I later found out a way to resolve this and still using ionic-native/http/ngx
Hope this will help others as well.
this.http.setDataSerializer('multipart')
formData.set('user_hash', 'xxxxx')
formData.set('activities_id', this.activities_id)
var url = environment.api_host + "/activities/log/images"
this.http.sendRequest(url, {
method: "post",
data: formData,
headers: this.headers,
timeout: 60,
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
}
This works
params:
{}
body:
[Object: null prototype] {
user_hash:
'xxxxxx',
activities_id: '12' }
files:
[ { fieldname: 'reports',
originalname: '1590642736754.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
buffer:
<Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 48 00 48 00 00 ff e1 00 58 45 78 69 66 00 00 4d 4d 00 2a 00 00 00 08 00 02 01 12 00 03 00 00 00 01 00 01 ... >,
size: 10857214 } ]