nodejs res.download()文件

时间:2017-06-11 17:18:28

标签: javascript node.js

我对nodejs和东西很陌生,我一直在研究如何从nodejs服务器上传和下载文件

上传部分工作正常,问题是下载部分

我写的代码没有错误但是,文件本身没有下载,我不知道我哪里出错了

这是我的uploadss.js文件

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

这里是包含html和javascript的indexss.ejs文件

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

2 个答案:

答案 0 :(得分:0)

您使用filename参数覆盖路径。试试这个:

res.download(path);

并阅读 res.download(路径[,文件名] [,fn])https://expressjs.com/en/api.html

答案 1 :(得分:0)

尝试以下代码

服务器

var app = express();
var fs = require('fs');
app.get('/image', function (req, res) {
    var path_image = req.headers.path;
    var src = fs.createReadStream(path_image);
    src.on('open', function () {
        src.pipe(res);
        log.info('down completed: ' + path_image);
    });
    src.on('error', function (err) {
        log.error('' + err);
    });
});

path_image 是您的文件路径,我使用发送的客户端信息

java-client 使用库https://github.com/koush/ion

Ion.with(MainActivity.this)
    .load("http://IP:PORT/image")
    .setHeader("path", path_image_on_server)
    .progress(new ProgressCallback() {
        @Override
        public void onProgress(long downloaded, long total) {
            Log.e("bc", "" + downloaded + " / " + total);
        }
    })
    .write(new File(path_image_save_file))
    .setCallback(new FutureCallback<File>() {
        @Override
        public void onCompleted(Exception e, File file) {
            if (e != null) {
                Log.e("bc", e.toString());
            }
            if (file != null) {
                Log.e("bc", file.getAbsolutePath());
            }
       }
   });