3

我正在尝试上传文件(图像),上传很好,文件存储在Mongo中,并且与原始文件具有相同的内容类型和相同的大小,然后当我尝试下载它时,文件已损坏但保持相同的内容类型(如果我上传pdf,它被识别为pdf,如果它是png,它也被识别,但我无法打开它们)。我不明白这有什么问题,它非常简单和标准。

对于来自客户端的上传,我使用 angular ng-upload,对于下载,它是对代码中定义的路由的简单 GET 请求。

编辑:该文件已很好地上传到服务器上,所以问题是当我尝试从 GridFS 读取它时。下载的文件比上传的大!所以文件不是原始文件并且已损坏,为什么?

这是我的代码。

//BACKEND

//ROUTES   
var multer  = require('multer');
var upload = multer({ dest: './tmp/'});
router.post('/:id/logo',upload.single('file'), uploadFile);
router.get('/:id/logo', getFile);

//Controller
var Grid = require('gridfs-stream');
var mongoose = require('mongoose');
var fs = require('fs');

uploadLogo = function(req, res) {
    var gfs = Grid(mongoose.connection.db, mongoose.mongo);
    var writeStream = gfs.createWriteStream();

    fs.createReadStream(req.file.path).pipe(writeStream);

    writeStream.on('close', function(file) {
        res.status(200).send({fileId: file._id});
    });
    writeStream.on('error', function(e) {
        res.status(500).send("Could not upload file");
    });
}

getFile = function(req, res) {

  var gfs = Grid(mongoose.connection.db, mongoose.mongo);

  // Check if the file exist
  gfs.findOne({ _id: req.params.id}, function(err, file) {
      if(err) {
          res.status(404).end();
      } else if(!file){
          res.status(404).end();
      } else {
          var readstream = gfs.createReadStream({
            _id: file._id
          });

          res.set('Content-Type', file.contentType);

          readstream.on('error', function (err) {
              res.send(500, err);
          });
          readstream.on('open', function () {
              readstream.pipe(res);
          });
      }
  });
}

//FRONT END
$scope.newFileUpload = function(file) {
  $scope.upload(file);
}

$scope.upload = function(file) {
  if (file && !angular.isUndefined(file.name)) {
    Upload.upload({
      url: 'api/' + $scope.myId + '/logo',
      fields: {
        'type': 'logo'
      },
      file: file
    }).success(function(data, status, headers, config) {
      $scope.imageId = data.fileId;
    }).error(function(data, status, headers, config) {
      console.log('file upload error status: ' + status);
    });
  }
};


//THE HTML
<div  class="drop-box"
        ngf-drop
        ngf-select
        ng-model="imageLogo"
        ngf-drag-over-class="dragover"
        ngf-allow-dir="true"
        accept="image/*"
        ngf-pattern="'image/*'"
        ngf-change="newFileUpload(imageLogo)"
        ngf-multiple="false"
        ngf-resize="{width: 200, height: 50}">
        Drop logo image here or click to upload</div>

        <input type="file" nv-file-select uploader="uploader"/>
4

0 回答 0