zoukankan      html  css  js  c++  java
  • node+express+static完成简单的文件下载

    不多说什么,直接上代码

    var express = require('express');
    var fs = require('fs')
    var path= require('path');
    var cors = require('cors');
    
    
    var app = express();
    app.use(cors());  
    
    var options = {
      dotfiles: 'ignore',
      etag: false,
      extensions: ['htm', 'html'],
      index: false,
      maxAge: '1d',
      redirect: false,
      setHeaders: function (res, path, stat) {
        res.set('x-timestamp', Date.now())
      }
    }
    app.use(express.static('public', options));
    
    
    app.get('/download',function(req, res, next){
        var currDir = path.normalize(req.query.dir),
            fileName = req.query.name,
            currFile = path.join(currDir,fileName),
            fReadStream;
            console.log(currDir );
            console.log(fileName );
        fs.exists(currFile,function(exist) {
            if(exist){
                res.set({
                    "Content-type":"application/octet-stream",
                    "Content-Disposition":"attachment;filename="+encodeURI(fileName)
                });
                fReadStream = fs.createReadStream(currFile);
                fReadStream.on("data",function(chunk){res.write(chunk,"binary")});
                fReadStream.on("end",function () {
                    res.end();
                });
            }else{
                res.set("Content-type","text/html");
                res.send("file not exist!");
                res.end();
            }
        });
    });
    app.listen(8088, function(){
        
        console.log('localhsot:8080')
    });

    使用方法:localhost:8080/download?dir='filedir'&name='filename',把这个直接放到a标签的href属性内就可以使用。

          dir:文件路径

          name:文件名称(带后缀)

  • 相关阅读:
    wso2使用
    wso2安装
    CLR 编译函数的两种结果的原因
    hduoj4311
    通过Git在本地局域网中的两台电脑间同步代码
    Git基本操作之强制推送覆盖仓库
    设置Mac共享网络给其他设备
    谷歌浏览器设置无图浏览模式
    加载到SGA中的库缓存对象超过阈值
    webBrowser 禁止屏蔽alert confirm open showModalDialog
  • 原文地址:https://www.cnblogs.com/guojikun/p/6915884.html
Copyright © 2011-2022 走看看