简体   繁体   English

使用nodejs上传文件,表达,平均堆栈

[英]File upload with nodejs, express, mean stack

I am new to Mean and nodejs. 我是Mean和nodejs的新手。 I have a old project with old dependencies. 我有一个带有旧依赖项的旧项目。 And I am trying to upload image file to server using angular js. 我正在尝试使用angular js将图像文件上传到服务器。 But it does not work. 但这行不通。 I don't know how to retrieve image file data, name, type, etc at both client and server side. 我不知道如何在客户端和服务器端检索图像文件数据,名称,类型等。

Client 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});

Server js 服务器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". req.files导致“未定义”。

Thanks 谢谢

You have to actually use the file upload middleware to get express to unpack that part of the request. 您必须实际使用文件上传middleware来表达要求,以解压缩请求的那一部分。 From the multer docs: 来自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)

Make sure to use you are using middleware for multipart/form-data eg multer https://github.com/expressjs/multer . 确保使用的中间件用于multipart / form-data,例如multer https://github.com/expressjs/multer

Also, Check if there is CORS error. 另外,检查是否存在CORS错误。 You can install cors npm module for solving that. 您可以安装cors npm模块来解决该问题。 https://www.npmjs.com/package/cors https://www.npmjs.com/package/cors

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM