Packy
Packy

Reputation: 3573

Nativescript Image Upload

I am trying to upload an image I am taking from the camera but its not working with HTTP module. The backend developer said I need to:

The POST method to use is ‘multipart/form'. The image file will use the field name of ‘image’ (this will be passed in to the API PHP in $_FILES).

To pass in the ‘function’ : ‘mpostUserAvatar’ and the ‘userID’ : 123456 use the 'application/x-www-form_urlencoded'. This will pass into the $_POST for the API PHP.

In the past I used the HTTP module to post to their API like:

const requestBody = { 
                    function: 'mpostUserAvatar',
                    userID: this.$store.state.user.id
                }

                this.$http.request({
                    url: this.$apiURL,
                    method: "POST",
                    headers: { "Content-Type": "application/x-www-form-urlencoded"},
                    content: this.$qs.stringify(requestBody)
                }).then((response) => {

                    this.$loader.hide()

                    const agResponse = response.content.toJSON();

                    console.dir( agResponse)

                }, (error) => {
                    console.log(error)
                });

Now if I add and image i tried:

const requestBody = { 
                    function: 'mpostUserAvatar',
                    userID: this.$store.state.user.id,
                    image: avatar //this is an image asset instance
                }

Also tried changing the content type to:"Content-Type": "multipart/form"

How can I upload a file with "Content-Type": "multipart/form" and also send through parameters ( function and userID ) using "Content-Type": "application/x-www-form-urlencoded"

Upvotes: 2

Views: 730

Answers (2)

Codedreamer
Codedreamer

Reputation: 1702

I've got a solution for you. To upload image using nativescript background http is now easy using a file stream method on your backend server.

https://www.ekpotoliberty.com/read/NativeScript-Image-Uploading-to-NodeJs-Api-+-Cloudinary-using-NativeScript-Background-HTTP/5dad52c76dc813685f8da26f

Follow the link above this will help you get through for nativescript core.

Upvotes: 0

Manoj
Manoj

Reputation: 21908

Multipart upload is not supported by the Http module. You have to either convert the image into base64 string and send it to server Or use the nativescript-background-http plugin which supports multi-part upload.

Update:

You will find an example for sending additional parameters in the ReadMe file.

var params = [
   { name: "function", value: "mpostUserAvatar" },
   { name: "userID", value: this.$store.state.user.id },
   { name: "image", filename: file, mimeType: "image/jpeg" }
];
var task = session.multipartUpload(params, request);

Upvotes: 2

Related Questions