9

I want to upload a file to a storage container using the Loopback storage service.

But the .upload() method expects a request object. But what if I want to upload an existing file that's not coming from a submitted form?

Do I need to fake a POST request in order to make the upload handler happy? Seems like there must be a better way.

xangy
  • 1,185
  • 1
  • 8
  • 19
Arne
  • 6,140
  • 2
  • 21
  • 20
  • Not tried,but there is method to get stream http://apidocs.strongloop.com/loopback-component-storage/#storageservice-prototype-uploadstream. This returns stream, you can use pipe and simply upload existing file using stream. – Rohit Harkhani Mar 07 '16 at 06:29

1 Answers1

3

As @RohitArkani hinted, the file app-cloud.js contains a version 1 example of file upload which uses storageService.uploadStream(container, file, [options], Callback).

var s3 = new StorageService({
  provider: 'amazon',
  key: "your-amazon-key",
  keyId: "your-amazon-key-id"
});

var fs = require('fs');
var path = require('path');
var stream = s3.uploadStream('con1', 'test.jpg');
fs.createReadStream(path.join(__dirname, 'test.jpg')).pipe(stream);

It seems (but see the comment) that in version 2, you get the storage service via

var ds = loopback.createDataSource({
  connector: require('loopback-storage-service'),
  provider: 'amazon',
  key: '...',
  keyId: '...'
});
var Container = ds.createModel('container');

instead. Then, call Container.uploadStream(...).

serv-inc
  • 35,772
  • 9
  • 166
  • 188
  • 1
    It seems version 2 still needs to make use of the pipe method above, cause uploadStream just gets the stream for uploading and it's strange that there is no callback method to act on it (node_modules/loopback-component-storage/lib/storage-service.js) even though in the official doc it mentions about the callback.. https://apidocs.strongloop.com/loopback-component-storage/#storageservice-prototype-uploadstream – ralixyle Sep 19 '17 at 16:05