7

I'm having difficulties to upload a file from buffer via ssh2-sftp-client (https://www.npmjs.com/package/ssh2-sftp-client) I'm using Multer for uploading files, then I'm just targeting req.file.buffer to access the data to be uploaded via the sftp client like this:

sftp.connect({
host: 'some.IP.address.here',
port: '22',
username: 'username',
password: 'password'
})
.then(() => {
return sftp.put(req.file.buffer, '/var/www/bucket', false);
})
.catch((err) => {
console.log(err, 'catch error');
});

I'm not able to figure out how to assign a name to that uploaded file which is stored in req.file.originalname of the Multer object.

Btw, the ssh2-sftp-client returns following error:

Error: Failure image.routes.js:39 code:4 lang:"" message:"Failure" stack:"Error: Failure\n at SFTPStream._transform (/Users/petrfila/Apps/lifeIQ/liq-api/node_modules/ssh2-streams/lib/sftp.js:410:27)\n at SFTPStream.Transform._read (_stream_transform.js:185:10)\n at SFTPStream._read (/Users/petrfila/Apps/lifeIQ/liq-api/node_modules/ssh2-streams/lib/sftp.js:181:15)\n at SFTPStream.Transform._write (_stream_transform.js:173:12)\n at doWrite (_stream_writable.js:406:12)\n at writeOrBuffer (_stream_writable.js:392:5)\n at SFTPStream.Writable.write (_stream_writable.js:290:11)\n at Channel.ondata (_stream_readable.js:646:20)\n at Channel.emit (events.js:127:13)\n at addChunk (_stream_readable.js:269:12)\n at readableAddChunk (_stream_readable.js:256:11)\n at Channel.Readable.push (_stream_readable.js:213:10)\n at SSH2Stream.<anonymous> (/Users/petrfila/Apps/lifeIQ/liq-api/node_modules/ssh2/lib/Channel.js:166:15)\n at SSH2Stream.emit (events.js:127:13)\n at parsePacket (/Users/petrfila/Apps/lifeIQ/liq-api/node_modules/ssh2-streams/lib/ssh.js:3444:10)\n at ... __proto__:Object {constructor: , name: "Error", message: "", …} constructor:function Error() { … } message:"" name:"Error" toString:function toString() { … } __proto__:Object {constructor: , __defineGetter__: , __defineSetter__: , …} catch error

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Petr Fila
  • 83
  • 6

1 Answers1

0

A bit late, but in case it helps.....

The version you were using was a little buggy and had very poor error handling. This has been resolved in later versions. Also, handling of relative path names was not consistent. This has also been fixed.

To upload a file and give it a remote file name, make sure the remote path includes the file name and not just the destination directory e.g.

let client = new Client();
client.connect(config)
.then(() => {
   return client.put(buffer.data, '/path/to/new-file-name');
.then(f => {
   console.log(`File uploaded to ${f}`);
.catch(err => {
  console.log(`Error: ${err.message}`);
});

NOte that if you can just use a local filename rather than a buffer or stream, you can use fastPut(), which is faster than put() because it does the transfer in parallel. However, it can onlyu work with path name strings.

Tim X
  • 4,158
  • 1
  • 20
  • 26