nolags nolags - 10 days ago 6
Node.js Question

Provide modified uploaded file as download AngularJS NodeJS

I have a Multer upload in my frontend:

<form id="uploadForm" ng-submit="upload.submit">
<input id="file" type="file" name="file" >
<input type="submit" value="Upload" id="submit" class="btn btn-primary" >
</form>


in my upload controller:

this.submit = function(){
$http.post('/upload').then(function success(response){
}, function error(response){
})
}


upload NodeJS with Multer:

var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '../uploads);
},
filename: function (req, file, cb) {
cb(null, file.originalname);
}
});

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

router.post('/upload', upload.single('file'), function(req, res, next){

if(!req.file) {
res.status(400);
res.send({error: 'Datei nicht vorhanden'});
}
res.send({filename: req.file.filename});
}) ;


how can I get this file name in a nother
router.get
request?

In my NodeJS I'm saving the file to the server, so I know that path. (../uploads/)

I want to provide the downloaded file for an download to the client again with
<a href="http://<path to file>">Download</a>
but how do I get the filename the user uploaded ?
To make this download work?

Thank you in advance.

Answer

As I said in the comment, your form is wrong. Check out angularJs form submittion: https://docs.angularjs.org/api/ng/directive/ngSubmit

As for your file upload, check this: https://github.com/danialfarid/ng-file-upload

I noticed you are using multer, here you have an example from an app of mine:

var multer  = require('multer');
var path = require('path');
var fs = require('fs');

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

With this three things you should be able to upload a file and receive back its name. Start slowly and step by step and you will make it work.

Comments