如何在节点js中下载服务器文件?

时间:2018-08-16 23:31:31

标签: javascript jquery node.js

能否请您告诉我如何在节点js中下载服务器文件

这是我的代码 Node js代码(请求代码)

var express = require('express');
var multer = require('multer');
var bodyParser = require('body-parser');
var cors = require('cors');
var app = express();
var path = require('path');
var PORT = process.env.PORT || 3000;


// use of body parser
app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(bodyParser.json());
app.use(cors());



app.get('/download', function(req, res){
    console.log(__dirname);
    var file = path.join(__dirname , '/uploads/file-1534458777206.xlsx');
    console.log(file)
    res.download(file); // Set disposition and send it.
});




app.listen(PORT, () => {
    console.log(`App is listening to ${PORT}`);
})

我正在客户上这样要求

$('.download').on('click', function () {
            $.ajax({
                url: 'http://localhost:3000/download',
                type: 'GET',
                dataType: 'json',
                success: function (data) {
                    console.log('data')
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    // Handle errors here
                    console.log('ERRORS: ' + textStatus);
                    // STOP LOADING SPINNER
                }
            });

在控制台上出现错误

ERRORS: parsererror
3index.html?_ijt=9lu9erpan2oq6qf28851ngj0ra:32 ERRORS: parsererror
2index.html?_ijt=9lu9erpan2oq6qf28851ngj0ra:32 ERRORS: parsererror

服务器日志

C:\Users\B0207296\WebstormProjects\uploadFile\server
C:\Users\B0207296\WebstormProjects\uploadFile\server\uploads\file-1534458777206.xlsx

为什么文件没有下载到客户端,因为我提到文件存在于上面的URL中

1 个答案:

答案 0 :(得分:0)

要通过ajax获取文件内容: 只需删除dataType,您的文件就会被解析为json,从而导致错误。

$('.download').on('click', function () {
     $.ajax({
         url: 'http://localhost:3000/download',
          type: 'GET',
          success: function (data) {
              console.log(data); // File data
          },
          error: function (jqXHR, textStatus, errorThrown) {
              // Handle errors here
              console.log('ERRORS: ' + textStatus);
              // STOP LOADING SPINNER
          }
      });

下载文件最好是用户虚拟链接

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

</head>
<body>
<b class="download">Download Here</b>
<script>
$('.download').on('click', function () {
    var link = document.createElement('a');
    link.href = 'http://localhost:3000/download';
    var e = document.createEvent('MouseEvents');
    e.initEvent('click', true, true);
    link.dispatchEvent(e);
  })
</script>

</body>
</html>