Anil Samuel
Anil Samuel

Reputation: 31

multipart/mixed with blob using axios

The curl command below works for the API call.

curl -k --user "un:$PASSWORD" -X POST -H "Content-type: multipart/mixed" -F "blob=@binaryfile" -F 'metadata={"prop1":"v1","prop2":"v2"};type=application/json' https:///api/v2.0/entity

How could I achieve the same using nodejs ?

        formData.append('blob', fs.createReadStream(binaryfile))
        formData.append('metadata', fs.createReadStream(jsonfile))
        const config = {
            method: 'POST',
            url: 'https://<host>/api/v2.0/entity',
            headers: {
                'Content-Type': 'multipart/mixed',
                'Accept': 'application/json'
            },
            data: formData
        }

        return await axios(config).then(function (response) {
            return response.data
        }).catch(error => {
            return error
        })

Upvotes: 1

Views: 41

Answers (1)

Noah Pragin
Noah Pragin

Reputation: 35

I am writing this answer assuming your jsonfile variable contains the properties you need in the metadata and the authentication used is HTTP Basic Authentication. If not, let me know below, and I will correct my answer.

The only thing you are missing in your request is the password. Create a variable and use it like below, or replace my usage of a constant with a value you declare in your .env file:

const PASSWORD = 'password'; //You could also use env variable

formData.append('blob', fs.createReadStream(binaryfile))
    formData.append('metadata', fs.createReadStream(jsonfile))
    const config = {
        method: 'POST',
        url: 'https://<host>/api/v2.0/entity',
        headers: {
            'Content-Type': 'multipart/mixed',
            'Accept': 'application/json'

            //Use the Authorization header for your password
            'Authorization': 'Basic ${Buffer.from('un:' + 
                PASSWORD).toString('base64')}'

        },
        data: formData
    }

    return await axios(config).then(function (response) {
        return response.data
    }).catch(error => {
        return error
    })

Upvotes: 2

Related Questions