使用nodejs、express、mean stack上传文件

File upload with nodejs, express, mean stack

我是 Mean 和 nodejs 的新手。我有一个具有旧依赖项的旧项目。我正在尝试使用 angular js 将图像文件上传到服务器。但它不起作用。我不知道如何在客户端和服务器端检索图像文件数据、名称、类型等。

客户端js

$scope.uploadFile = function(files,index) {

    console.log("uploading file");
    console.log("sticker index:" + index);
    console.log("StickerGroupID:"+ $scope.stickergroup._id);
console.log("file:"+ files[0].name);

console.log("sticker :  " + $scope.stickergroup.stickers[index].stickername );

$scope.stickergroup.stickers[index].stickerFileName = files[0].name ;
    console.log("sticker path now:" +$scope.stickergroup.stickers[index].stickerFileName);

  var fd = new FormData();

  fd.append("file", files[0]);
  fd.append("filename", files[0].name);

//put an upload file to temp location.
$http.post("/stickergroups/uploadstickers", fd, {
//   withCredentials: true,
  headers: {'Content-Type': undefined },
  transformRequest: angular.identity});

服务器 js

exports.uploadTempFile = function(req, res) {

console.log("uploading start");

console.log("file required :" +req.files);
var imagefile = req.files.file;
var tempDirectorySticker = tempDirectory + imagefile.originalFilename;

console.log("temp directory" + tempDirectorySticker );

fs.readFile(imagefile.path, function (err, data) {
    fs.writeFile(tempDirectorySticker, data, function (err) {
    res.redirect("back");
    });
 });};

req.files is resulting "undefined".

谢谢

您必须实际使用文件上传 middleware 才能快速解压缩该部分请求。来自 multer 文档:

var express = require('express')
var multer  = require('multer')

var app = express()
app.use(multer({ dest: './uploads/'}));

console.log(req.body)
console.log(req.files)

确保使用您正在使用的中间件 multipart/form-data 例如multer https://github.com/expressjs/multer.

另外,检查是否存在CORS错误。您可以安装 cors npm 模块来解决这个问题。 https://www.npmjs.com/package/cors