html5 - node.js下载失败,求大神解释
伊谢尔伦
伊谢尔伦 2017-04-17 15:17:43
0
2
468

使用express框架下载文件,但是失败了,直接看代码

<!DOCTYPE html>
<html>
<head>
    <title>express 主页</title>
    <meta charset="utf-8">
    <script type="text/javascript" src="jquery.min.js"></script>
</head>
<body>
<p>
I love you!
</p>
<button>click there to download a pictutre</button>
<script type="text/javascript">
$(function(){
    $('button').click(function(){
            $.ajax({
                url:'/download',
                type:'get',
                success:function(result){
                    alert("Resquest has been received!");
                }
            })
    })
})

</script>

</body>
</html>

以下是node.js代码

    var express = require("express");
var app = express();

app.use(express.static('public'));
app.locals.title = "My app";
app.get("/",function(req,res){

console.log("resquest has been received!");

res.sendFile("public/index.html");
res.end();
})

app.get("/download",function(req,res){

    
    res.download('public/example.jpg','example.jpg',function(err){
        if(err)
            console.log(err);
        else
            console.log("download successfully");
    });
})
app.listen(3000);

console.log("OK");


求解疑

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

Antworte allen(2)
小葫芦

你的下载按钮我建议直接写成

<a href="/download" download>下载</a>

http://www.expressjs.com.cn/4...
注意res.download方法的第一个参数

res.download('/report-12345.pdf', 'report.pdf', function(err){
  if (err) {
    // Handle error, but keep in mind the response may be partially-sent
    // so check res.headersSent
  } else {
    // decrement a download credit, etc.
  }
});

然后你的图片虽然尺寸很大,但是太模糊了。。。

Peter_Zhu

index.html

<!DOCTYPE html>
<html>
<head>
    <title>express 主页</title>
    <meta charset="utf-8">
    <script type="text/javascript" src="jquery.min.js"></script>
</head>
<body>
<p>
I love you!
</p>
    <a href="/download" download>下载</a>
</body>
</html>

node.js

var express = require("express");
var app = express();

app.use(express.static('public'));
app.locals.title = "My app";
app.get("/",function(req,res){

console.log("resquest has been received!");

res.sendFile("public/index.html");
res.end();
})

app.get("/download",function(req,res){

    res.download('public/example.jpg', 'example.jpg',function(err){
        if(err)
            console.log(err);
        else
            console.log("download successfully");
    });
})
app.listen(3000, function(err) {
  if(err) console.error(err);
  console.log("OK");
});

你可以浏览器单独访问http://localhost:3000/download看看能不能下载下来,你现在直接404后台服务都没ready,先别前后端的联调吧。

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage