How to upload file using multipart/form-data in nativescript?


#1

Hi,

I’m going to upload images and text using multiform-data.
but I failed.

post_part_deviation(project_id, part_id, p_deviation, s_solution){
let body: any = {
project_id: project_id,
part_id: part_id,
photo_deviation:p_deviation,/////image url
photo_solution:s_solution/////////////image url
};
let str = [];
for(let p in body) {
str.push(encodeURIComponent§ + “=” + encodeURIComponent(body[p]));
}
body = str.join("&");
let headers = new Headers();
headers.append(“Content-Type”, “multipart/form-data”);
let options = new RequestOptions({ headers: headers });
console.log(body);
return this.http.post(“http://url/api/project_part_deviations”, body, options)
.toPromise()
.then((data) => {
console.log(“DATA”);
console.log(JSON.stringify(data.json()));
})
.catch(this.handleErrors);
}
handleErrors(error: Response) {
console.log(JSON.stringify(error.json()));
return Observable.throw(error);
}

Please check my code.


#2

hi, could you give us some information about the error that occurs? Also you can format your code so it’s easier to read by using the </> button.


#3

Nativescript support file upload functionality using multipart/form-data ?


#4

did you do a quick Google on this? http://stackoverflow.com/questions/39334643/how-to-upload-file-using-multipart-form-data-in-nativescript


#5

A couple months ago I added Multipart-form upload capability to
https://github.com/NativeScript/nativescript-background-http plugin.

To my knowledge this is the ONLY way currently to do multipart-form uploads.

Nathanael A.


#6

?so, this “Content-Type”: “application/octet-stream” is the same multiPart formdata? i dont need change anything in the server to use this content type?


#7

Actually you can omit “Content-Type”: “application/octet-stream” if it’s not needed for your backend.
Here is an example of file upload to QuickBlox (which uses AWS S3 under the hood with “multipart/form-data” supported)

I just pass

var request = {
            url: uploadUrl,
            method: "POST"
};

and use

var task = session.multipartUpload(uploadParams, request);


#8

I also needed this. so i created a plugin https://github.com/dotnetdreamer/nativescript-http-formdata