nativescript-http-formdata
Version:
A NativeScript plugin to post/upload file as multipart/form-data to server.
62 lines • 2.65 kB
JavaScript
import { Common } from './TNSHttpFormData.common';
export class TNSHttpFormData extends Common {
constructor() {
super();
}
post(url, params, options) {
return new Promise((resolve, reject) => {
try {
let client = new okhttp3.OkHttpClient();
let builder = new okhttp3.MultipartBody.Builder();
const FORM_MEDIA_TYPE = okhttp3.MediaType.parse("multipart/form-data");
builder.setType(FORM_MEDIA_TYPE);
for (let param of params) {
if (param.fileName && param.contentType) {
const MEDIA_TYPE = okhttp3.MediaType.parse(param.contentType);
builder.addFormDataPart(param.parameterName, param.fileName, okhttp3.RequestBody.create(MEDIA_TYPE, param.data));
}
else {
builder.addFormDataPart(param.parameterName, param.data);
}
}
let requestBody = builder.build();
let reqWithURL = new okhttp3.Request.Builder()
.url(url);
if (options && options.headers) {
for (let k in options.headers) {
reqWithURL.addHeader(k, options.headers[k]);
}
}
const request = reqWithURL
.post(requestBody)
.build();
let callback = new okhttp3.Callback({
onResponse: (call, response) => {
let body;
try {
body = JSON.parse(response.body().string());
}
catch (e) {
body = response.body().string();
}
let customResponse = {
headers: response.headers().toString(),
statusCode: response.code(),
statusMessage: response.message(),
body: body
};
resolve(customResponse);
},
onFailure: (call, response) => {
reject(response);
}
});
client.newCall(request).enqueue(callback);
}
catch (e) {
reject(e);
}
});
}
}
//# sourceMappingURL=TNSHttpFormData.android.js.map