yussan yussan - 1 month ago 20
Node.js Question

Upload File Using NPM Request from new Formdata()

i'am develop backend using

node-js
and https://www.npmjs.com/package/request to handdle request to main api.

has successfully to send data in the form of string or a number. but I have a problem to send the file. before getting to the request module, i have convert all request from client using

new formdata()


end this is what i code using NPM request

export function requestAPI(method='GET', endpoint='', params={}, callback)
{
let token = ''
if(params.token)
{
token = params.token;
delete params.token;
}

//set query
if(params.query)
{
endpoint = `${endpoint}?${Url.serialize(params.query)}`
delete params.query
}

//set options
let options = {
method: method,
uri: `${process.env.API_HOST}${endpoint}`,
timeout: 6000,
headers: {
'auth' : token
},
};

// upload files
// ???

// using POST method
if(method === 'POST') {
options['form'] = params;
}

// is upload a file - request via multipart/form-data


//start request
try {
request( options , function(error, response, body){
if(error)
{
console.log(error)
return callback(httpException(500));
} else //success
{
return callback(JSON.parse(body));
}
})
} catch(err) {
return callback(httpException(500, err.message+', '+err.stack));
}
}

Answer

thanks for help guys, finaly i found the answer to solved it.

the problem on this line

if(method === 'POST') {
  options['form'] = params;
}

i just change to this, to make it works

if(method === 'POST') {
  options['formData'] = params;
}

and this is the complete of codes

export function requestAPI(method='GET', endpoint='', params={}, callback)
{
    let token = ''
    if(params.token)
    {
        token = params.token;
        delete params.token;
    }

    //set query
    if(params.query)
    {
        endpoint = `${endpoint}?${Url.serialize(params.query)}`
        delete params.query
    }

    //set options
    var options = {
        method: method,
        uri: `${process.env.API_HOST}${endpoint}`,
        timeout: 30000,
        headers: {
            'auth' : token
        },
    };

    // using POST method
    if(method.toLowerCase() === 'post') {
        options.formData = params;

        // upload files
        if(options.formData.files)
        {
            const files = options.formData.files
            delete options.formData['files']

            Object.keys(files).map(n => {
                options.formData[n] = {
                    value: fs.createReadStream(files[n]._writeStream.path),
                    options: {
                        filename: files[n].name,
                        type: files[n].type
                    }
                }
            })
        }
    }

    //start request
    try {
        request( options , function(error, response, body){
            if(error)
            {
                return callback(httpException(500));
            } else //success
            {
                return callback(JSON.parse(body));
            }
        })
    } catch(err) {
        return callback(httpException(500, err.message+', '+err.stack));
    }
}
Comments