Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload files - sails.js

I can download images and pdf, but I can't download documents files (.doc .pptx .odt ...)

when download Documents(.doc .pptx .odt ...) are downloaded as .ZIP only XML files. What I can do?

I'm using : fill out upload file docs

upload: function (req, res) {
  req
    .file('avatar')
    .upload({
      maxBytes: 10000000
    }, function whenDone(err, uploadedFiles) {
      if (err) {
        return res.negotiate(err);
      }

      // Generate a unique URL where the avatar can be downloaded.
      avatarUrl = require('util').format('%s/user/avatar/%s', sails.getBaseUrl(), req.session.User.id_user),
      // Grab the first file and use it's `fd` (file descriptor)
      avatarFd = uploadedFiles[0].fd

      var SkipperDisk = require('skipper-disk');
      var fileAdapter = SkipperDisk(/* optional opts */);

      // Stream the file down
      fileAdapter.read(avatarFd).on('error', function (err){
        return res.serverError(err);
      }).pipe(res);

  });
},
like image 917
Danieledu Avatar asked Dec 22 '14 18:12

Danieledu


1 Answers

I use this at Windows and it have no problems.

upload  : function (req, res) {
  req.file('avatar').upload({
    maxBytes: 10000000
  }, function whenDone(err, uploadedFiles) {
    if (err) {
      return res.negotiate(err);
    }

    var avatarFd = uploadedFiles[0].fd;

    res.ok(avatarFd);

  });
},
download: function (req, res) {
  var location = req.param('fd');
  var SkipperDisk = require('skipper-disk');
  var fileAdapter = SkipperDisk(/* optional opts */);
  fileAdapter.read(location).on('error', function (err) {
    return res.serverError(err);
  }).pipe(res);
}

First upload it using /somecontroller/upload with multipart/form-data, it will return an fd location. And download it using this url

http://localhost:1337/somecontroller/download?fd=[fd-from-upload-return]

Controller name and host name is depends on your application configuration.

Using fd full path is just for an example, in prodtion later you should use your own controller to address from uploaded folder to return file that has been uploaded, it's usually on .tmp/uploads/.

like image 161
Andi N. Dirgantara Avatar answered Sep 29 '22 03:09

Andi N. Dirgantara