Phyo
Phyo

Reputation: 692

File upload with nodejs, express, mean stack

I am new to Mean and nodejs. I have a old project with old dependencies. And I am trying to upload image file to server using 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

$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

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".

Thanks

Upvotes: 1

Views: 732

Answers (2)

NeiL
NeiL

Reputation: 801

Make sure to use you are using middleware for multipart/form-data e.g. multer https://github.com/expressjs/multer .

Also, Check if there is CORS error. You can install cors npm module for solving that. https://www.npmjs.com/package/cors

Upvotes: 0

user4510143
user4510143

Reputation:

You have to actually use the file upload middleware to get express to unpack that part of the request. From the multer docs:

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

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

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

Upvotes: 1

Related Questions