我想尝试回答这个问题……有趣的是,2 年零 2 个月后,我无法弄清楚如何轻松解决相同的问题。
我正在尝试从以下响应中获取附件:
...
标头:{'缓存控制':'no-cache="set-cookie"','内容类型':'multipart/related;boundary="----=_Part_61_425861994.1525782562904";type="application/ xop+xml";start="";start-info="text/xml"',
...
正文:'--------=_Part_61_425861994.1525782562904\r\n内容类型:应用程序/xop+xml;字符集=utf-8;type="text/xml"\r\nContent-Transfer-Encoding: 8bit\r\nContent-ID: \r\n\r\n....\r\n------=_Part_61_425861994.1525782562904 \r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\nContent-ID: \r\n\r\n�PNG\r\n\u001a\n\u0000\ u0000\u0000\rIHDR\u0000\u0000\u0002,\u0000\u0000\u0005�\b\u0006\u0........二进制....
我尝试了 ws.js但没有解决方案。
我的解决方案:
var request = require("request");
var bsplit = require('buffer-split')
// it will extract "----=_Part_61_425861994.1525782562904" from the response
function getBoundaryFromResponse(response) {
var contentType = response.headers['content-type']
if (contentType && contentType.indexOf('boundary=') != -1 ) {
return contentType.split(';')[1].replace('boundary=','').slice(1, -1)
}
return null
}
function splitBufferWithPattern(binaryData, boundary) {
var b = new Buffer(binaryData),
delim = new Buffer(boundary),
result = bsplit(b, delim);
return result
}
var options = {
method: 'POST',
url: 'http://bla.blabal.../file',
gzip: true,
headers: {
SOAPAction: 'downloadFile',
'Content-Type': 'text/xml;charset=UTF-8'
},
body: '<soapenv: ... xml request of the file ... elope>'
};
var data = [];
var buffer = null;
var filename = "test.png"
request(options, function (error, response, body) {
if (error) throw new Error(error);
if (filename && buffer) {
console.log("filename: " + filename)
console.log(buffer.toString('base64'))
// after this, we can save the file from base64 ...
}
})
.on('data', function (chunk) {
data.push(chunk)
})
.on('end', function () {
var onlyPayload = splitBufferWithPattern(Buffer.concat(data), '\r\n\r\n') // this will get from PNG
buffer = onlyPayload[2]
buffer = splitBufferWithPattern(buffer, '\r\n-')[0]
console.log('Downloaded.');
})
我不确定它在大多数情况下是否有效。在我看来,它看起来像是不稳定的代码,所以我正在寻找更好的东西。