[英]how to download server file in node js?
您能否告訴我如何在Node 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中
要通過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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.