angular-file-upload到nodejs后端无法读取文件内容

时间:2016-11-22 20:13:47

标签: javascript angularjs node.js ng-file-upload

我使用角度文件上传,以前在我使用Laravel Lumen作为后端时工作但是我已经移动到Node并且无法返回上传的文件内容。

FRONT END ANGULAR

$scope.upload = Upload.upload({
    url: ENV.apiEndpoint + '/upload',
    method: 'POST',
    data: {
        fname: $scope.fname
    },
    file: file
}).progress(function(evt) {

}).success(function(data, status, headers, config) {
});

BACK END NODE

上传/ index.js

'use strict';

var express = require('express');
var controller = require('./upload.controller');

var router = express.Router();
var multer = require('multer');

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './my-uploads');
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now());
  }
})

var upload = multer({ storage: storage });


router.post('/', upload.single('file'), controller.index);

module.exports = router;

上传/ upload.controller.js

'use strict';

var _ = require('lodash');
var db = require('../../db');
var https = require('https');
var Q = require('q');
var fs = require('fs');
var multer = require('multer');

exports.index = function(req, res, next) {
    console.log(req.files.file);
    res.status(204).end();
};

旧Laravel Lumen请求

public function data(Request $request) {

    $path_parts = pathinfo($_FILES["file"]["name"]);
    $extension = $path_parts['extension'];
    $contents = file_get_contents( $_FILES['file']['tmp_name'] );
    return response()->json(['type'=> $extension, 'content'=> $contents]);
}

我要做的就是上传文件,但只将文件的内容再次返回到前端我不希望存储文件。

1 个答案:

答案 0 :(得分:0)

这里有一个例子,你有几个错误。看看

 var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'public/images/banks')
  },
  filename: function (req, file, cb) {
    crypto.pseudoRandomBytes(16, function (err, raw) {
      cb(null, raw.toString('hex') + path.extname(file.originalname));
    });
  }
});
var upload = multer({storage: storage});

router.post('/uploadImage', upload.single('file'), function (req, res, next) {
  if(!req.file) {
    res.status(400);
    res.send({error: 'No se pudo subir el archivo'});
  }

  res.send({filename: req.file.filename});
});