API-Services method and multipart/form-data

Hello im trying to create a method which allows the user to upload a file (e.g. an image) and some additional data as a multipart/form-data request. i would like to process the file and saving a reference into the database.

the curl command

curl -i "https://eu-api.backendless.com/XXXXXXXX-A78D-BFC4-XXXX-XXXXXXXXXXX0/09A2FC7F-XXXA-4X77-XXXX-XXXXXXXXXXX/services/my_service/my_method" -F file=@test.txt

results into this error

{"code":14004,"message":"Service invocation failed: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value\n at [Source: (ByteArrayInputStream); line: 1, column: 3]","errorData":{}}

Hi Jan,

Welcome to the Backendless Community.

An API service running in Backendless can accept requests only with the application/json Content-Type for POST and PUT requests. Sending multipart/form-data to an API service will not work. If you need to send a file, you’d need to encode the file contents in request body. There are several options for that, for instance, it can be a base64 encoded string or a byte array.

Regards,
Mark

Hi Mark,

could you please give me an example of how to send and receive the byte array in the request body?

Thanks a lot.

Jan

Hello @Jan_Fischer

your method should receive string as argument, check the following example:


Or you can use it as a code:

async function methodWithByteArray(base64Arg) {
    const byteArr = (convertDataFromTo(base64Arg, 'base64', 'bytes'));

    return (convertDataFromTo(byteArr, 'bytes', 'utf8'))
}

function convertDataFromTo(data, from, to) {
    if (from === to) {
        return data
    }

    if (typeof Buffer !== 'undefined') {
        const buffer = from === 'bytes' ? data : Buffer.from(data, from)
        return (to === 'base64' || to === 'utf8') ? buffer.toString(to) : buffer
    }

    if (typeof atob === 'undefined' || typeof btoa === 'undefined' || typeof TextDecoder === 'undefined' || typeof TextEncoder === 'undefined') {
        throw new Error('Data converter is not allowed in the env, it requires [atob, btoa, TextDecoder]')
    }

    if (from === 'base64') {
        data = atob(data)
    }
    if (from === 'bytes') {
        data = (new TextDecoder('utf8')).decode(data)
    }
    if (to === 'utf8') {
        return data
    }
    if (to === 'base64') {
        return btoa(data)
    }
    if (to === 'bytes') {
        return (new TextEncoder()).encode(data).buffer
    }
}
1 Like

thanks a lot. just to be clear: any api service in backendless can only with the application/json Content-Type for POST and PUT requests, no matter if codeless or js service?

Hello @Jan_Fischer,

Yes, API services in Backendless only works with the Content-Type:application/json for the POST and PUT requests.

Regards,
Olha