附加base64编码的文件nodejs

时间:2018-07-11 15:36:29

标签: javascript node.js soapui

我正在尝试发送带有附件的肥皂请求。一切正常,除了我发送的附件始终为零字节。 soap服务器接受Base64编码的文件,而我已经实现了使用代码在Java中完成

OutputStream outputStream = new ByteArrayOutputStream()
outputStream.writeTo(fileOutputStream);
Base64.encode(outputStream.toByteArray())//argument passed to the function which sends this to the SOAP API

我想用node复制相同的内容,但是我不能这样做。以下是我用来实现此目的的功能。我正在从客户端读取一些文件,并尝试将其发送到SOAP API。我已在代码中标记了负责读取和附加数据的位置,其余仅作为参考。

function createSoapEntryWithAtt(req,response){
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        let filesArr = []
        for(objkeys in files){
            filesArr.push(files[objkeys])
        }
        return Promise.all(filesArr.map(item => {
            return new Promise((res,rej) => {
                var oldpath = item.path;
                var newpath = 'C:/user/' + item.name;
                **var data = fs.readFileSync(oldpath).toString('base64');
                let result = []
                for (var i = 0; i < data.length; i += 2)// trying to create a 64bit byte array
                    result.push('0x' + data[i] + '' + data[i + 1])**

                console.log(result)
                if(data)
                    res({ [`${item.name}`]: result }) 
                rej("Error occured")
            })

        })).then(data => {
            let url = config.url
            var credentials = {
                AuthenticationInfo: {
                    userName: "user",
                    password: "passwd"
                }
            }
            let args = {
                Notes: "Testing From Node App",
            }
            let count = 0
            for (index in data) {
                if (count <= 3) {
                    **for(keys in data[index]){
                        //console.log(data[index][keys])
                        args[`Attachment${++count}_Name`] = keys
                       args[`Attachment${++count}_Data`] = data[index][keys]//Attaching the file read  
                    }
                }**
            }
            soap.createClient(url, function (err, client) {
                client.addSoapHeader(credentials)

                client.CreateWorkInfo(args, function (err, res) {
                    if (err) {
                        console.log("Error is ----->" + err)
                    } else {
                        console.log("Response is -----> " + res)
                        response.end();
                    }
                })
            })

        })

    });

}

1 个答案:

答案 0 :(得分:0)

请忽略此问题....,如果有人在此问题上浪费了时间,谢谢您。该错误是我在args["Attachment${++count}_Name"] = keys args["Attachment${++count}_Data"] = data[index][keys]行中的粗心大意。在这里,当我在两行中增加计数时,附件名称将为1,然后在第二行中附件数据将为02,因此名称不包含任何数据。