Sunday, 11 June 2017

nodejs res.download() file

i'm pretty new to nodejs and stuff, and i;ve been researching on how to upload and download a file from a nodejs server

the upload part works just fine, the problem is the download part

the code i wrote has no errors but however, the file itself is not downloading, i have no idea where i went wrong

here's my uploadss.js file

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

var app = express();
var router = express.Router();

var storage =   multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, __dirname + '/uploads');
  },
  filename: function (req, file, callback) {
    callback(null, Date.now() + path.extname(file.originalname));
  }
});
var upload = multer({ storage : storage }).array('userPhoto',5);


app.set('views', __dirname + '/views');
app.get('/index', function(req, res){
  res.render('indexss.ejs');
});

app.use('/', router);

app.post('/api/photo', function(req, res){
    upload(req, res, function(err) {
         if(err) {
            return res.end("Error uploading file.");
        }
        res.end("File is uploaded");
    });
});

router.get('/download', function(req, res) { 
  var dir = path.resolve(".") + '/uploads/';
  fs.readdir(dir, function(err, list) { 
    if (err) 
      return res.json(err);
    else
      res.json(list);
  });

});

router.get('/download/:file(*)', function(req, res, next){ 
  var file = req.params.file;
  var path = require('path');
  var path = path.resolve(".") + '/uploads/' + file;
  res.download(path, file, function(err){
    if (err){
      console.log(err);
    } else {
      console.log('downloading successful');
    }
  });
});


app.listen(8080);

and here's the indexss.ejs file that contains the html and javascript

<html>
<head>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" ></script>

    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>

    <script>

        $(document).ready(function() {

            $('#uploadForm').submit(function() {
                $("#status").empty().text("File is uploading...");
                $(this).ajaxSubmit({
                    error: function(xhr) {
                        console.log(xhr);
                        status('Error: ' + xhr.status);
                    },
                    success: function(response) {
                        $("#status").empty().text(response);
                        console.log(response)
                    }
                });
                return false;
            }); 


            $.ajax({
                url: "/download",
                method: "get",
                success: function(data){
                    downloadArray = data;
                    for (i = 0; i < downloadArray.length; i++){
                        console.log(downloadArray[i]);
                        console.log(typeof downloadArray[i]);
                        $('#downloadList').append("<a href='#' onclick='downloadFile(this)'>" + downloadArray[i] + "</a><br>");

                    }
                }
            });
        });
        function downloadFile(selectedFile){
            fileToDownload = $(selectedFile).text();
            console.log(fileToDownload);
            $.ajax({
                url: "/download/" + fileToDownload,
                method: "get",
                success: function(){
                    console.log('successful downloading');
                }
            });
        }
    </script>  
</head>

<body>

    <form id="uploadForm"
        enctype="multipart/form-data"
        action="/api/photo"
        method="post">
        <input type="file" name="userPhoto" multiple />
        <input type="submit" value="Upload" name="submit">
        <input type='text' id='random' name='random'><br>
        <span id = "status"></span>
    </form>

    <div id='downloadList'></div>
</body>



via iam noone

No comments:

Post a Comment