下载函数GridFS和NodeJS

时间:2018-04-16 04:36:31

标签: javascript node.js gridfs

我创建了一个上传文件的脚本。上传部分没问题,但问题是下载。我试过this link in stackoverflow,我觉得它没有用,因为我没有得到任何物理文件下载,但我得到了204响应,这意味着管道成功了。我想获得一个可下载的文件。这是我的AJAX请求

_fileUploads.download = function(reload_on_return) {
  var filtered = root.fileUploads().filter(_ => _._id() == _fileUploads._id());
  var index = root.fileUploads.indexOf(filtered = filtered[0]);
  filtered = ko.toJS(filtered);

  swal({
    text: 'Are you sure you want to download the file?',
    buttons: true,
    icon: 'info'
  }).then(function(allowDelete) {
    if (allowDelete) {
      toastrTrigger('The File is being processed')
      $.ajax({
        type: 'GET',
        url: '/api/gridfs/files/' + filtered._id,
        statusCode: {
          204: function(response) {
            toastrTrigger('The File is being Downloaded')
            window.location = "/api/gridfs/files/" + filtered._id;
          }
        },
        error: function(xhr, status, error) {
          toastrTrigger('Bad request', undefined, 'error');
        }
      });
    }
  });
}

这是下载功能:

exports.gridFsFilesDownload = function(req, res) {

  gfs.findOne({
    _id: mongoose.Types.ObjectId(req.params.id),
    root: 'uploads'
  }, function(err, file) {

    if (err) {
      return res.status(400).send(err);
    } else if (!file) {
      return res.status(404).send(err);
    }

    console.log(file.filename)
    console.log(file.contentType)
    console.log(file._id)

    var readstream = gfs.createReadStream({
      _id: file._id,
      root: 'uploads'
    });

    console.log(mongoose.Types.ObjectId(req.params.id));
    console.log(req.params.id);

    res.set('Content-Type', file.contentType);
    res.set('Content-Disposition', 'attachment; filename="' + file.filename + '"');

    readstream.on("error", function(err) {
      res.end()
    });


    readstream.pipe(res);
    console.log(readstream.pipe(res));
    console.log('success')

    return res.status(204).send();

  });

};

0 个答案:

没有答案