Download files in API Restfull Nodejs

Asked

Viewed 1,815 times

2

I have an API I made based on a tutorial, where I can upload files:

Server.js

var express = require('express')
  , app = express()
  , bodyParser = require('body-parser')
  , multiparty = require('connect-multiparty');

  app.use(bodyParser.urlencoded({ extended: true }));
  app.use(bodyParser.json());
  var port = process.env.PORT || 8080;
  var router = express.Router();

  app.use('/api', router);

    /*insira as rotas aqui */
     router.route('/upload')
     .post(multiparty(), require('./controllers/uploads'));

  app.listen(port);

  console.log('conectado a porta ' + port);

Upload.js

var fs = require('fs');

    module.exports = function(req, res){
      res.setHeader("Access-Control-Allow-Origin", "*");
      var arquivo = req.files.file;
      var temporario = req.files.file.path;

      var novo = './uploads/' + req.files.file.name;
        fs.rename(temporario, novo, function(err){
            if(err){
                res.status(500).json({error: err})
            }
            res.json({message: "enviado com sucesso.", file: novo});
        })
    }

I can successfully upload it to an Api project folder, but what about downloading the uploads I do? How would that be? some example?

2 answers

0

If you do not need any validation to access the files you can just serve the files statically. To do this add in your file Server.js the following lines:

const path = require('path');

// ...

application.use('/arquivos', express.static(path.join(__dirname, 'uploads')));

And so you can access the file through URL of your project + /arquivos + the file name.

Delivering Static Files to the Express

To deliver static files such as images, CSS files, and Javascript files, use the express.Static middleware feature integrated into Express.

Pass the name of the directory that contains the static assets to the express.Static middleware function to start delivering the files directly. For example, use the following code to deliver images, CSS files, and Javascript files to a directory called public:

app.use(express.static('public'));

Now it is possible to load the files that are in the public directory:

http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html

0


I was able to solve it by doing it this way:

download js.

var fs = require('fs');
const http = require('http');

module.exports = function (req, res) {
    res.setHeader("Access-Control-Allow-Origin", "*");

    var file = __dirname + '/../uploads/foto.jpeg';
    res.download(file); // Set disposition and send it.
}

And in server.js I added:

router.route('/download')
     .get(multiparty(), require('./controllers/download'));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.