4

I need to add an file attachment to a soap request from node.js application.

I am able to send request with node-soap library, and now I need to add a file to the request.

I did it with a java client or with soapUI, but I have to do it in node.js, maybe it's possible to do that overriding default request object ?

Antoine
  • 4,456
  • 4
  • 44
  • 51

2 Answers2

6

I didn't find a solution with node-soap, I had to build manually my soap request :

var soapHeader = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Header/><soapenv:Body><ws:method>';
var soapFooter = '</ws:method></soapenv:Body></soapenv:Envelope>';

function sendSoapRequestWithAttachments(soap,files){
   var soapRequest = jsonToXml.buildObject(mail);
   var finalSoapRequest = soapHeader + soapRequest + soapFooter;
   var multipartMail = [];

    // Add soap request
    multipartMail.push({
        'Content-Type': 'text/xml; charset=utf-8',
        body: finalSoapRequest
    });
    // Add attachments
    if (files) {
        files.forEach(function (file) {
            multipartMail.push({
                'Content-Id': '<' + file.uuid + '>',
                'Content-Type': 'application/octet-stream',
                'Content-Transfer-Encoding': 'binary',
                body: fs.createReadStream(file.path)
            });
        });
    }
    var options = {
        uri: URL,
        method: 'POST',
        multipart: multipartMail
    };
    request.post(options, function (error, response) {
        ...
    }
}
Antoine
  • 4,456
  • 4
  • 44
  • 51
  • I have a SOAP server that expect the attachment at some input point, how I have to deal with this ? 'cause I don't see any reference to your attachment in your example – DevTheJo Oct 03 '18 at 18:08
2

I found a way to send attachment using node-soap using base64 encoding here is an example

import soap from 'soap'
import fs from 'fs'

async function main(){
  const filepath = '/path/to/attachment/file.extension'
  const client = await soap.createClientAsync(/* ... */)
  const result = await client.AnApiMethodAsync({
    expectedKeyForTheFile: await fs.readFileAsync(filepath, 'base64')
  })
}

main()
DevTheJo
  • 2,179
  • 2
  • 21
  • 25