spring mvc 文件下载

在web中下载的方式大多基于servlet,在web.xml中配置下载路径,这里再介绍json(转成base64字符串)和blob的使用方式

servlet

WEB-INF/web.xml

<!--url映射-->
<servlet-mapping>
	<servlet-name>DowloadServlet</servlet-name>
	<url-pattern>/servlet/dowloadFile</url-pattern>
</servlet-mapping>


<!--指定servlet-->
<servlet>
	<servlet-name>DowloadServlet</servlet-name>
	<servlet-class>com.xxxxxx.servlet.DowloadServlet</servlet-class>
</servlet>

servlet代码 

protected void download(String path, String fileName) {
        File file = new File(path);
        if (!file.exists()) {
            logger.error("下载的文件不存在 path=" + path + ",fileName=" + fileName);
        }
        //下载
        OutputStream out = null;
        BufferedInputStream in = null;
        try {
            getResponse().setCharacterEncoding("UTF-8");
            getResponse().setContentType("application/vnd.ms-excel");
            getResponse().setHeader("Content-Disposition", "attachment; filename=" + fileName);
            out = getResponse().getOutputStream();
            in = new BufferedInputStream(new FileInputStream(path));
            int line;
            while ((line = in.read()) != -1) {
                out.write(line);
            }
        } catch (Exception ex) {
            logger.error("下载文件失败 path=" + path, ex);
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (Exception ex) {
                    logger.error("关闭out异常 path=" + path, ex);
                }
            }
            if (null != in) {
                try {
                    in.close();
                } catch (Exception ex) {
                    logger.error("关闭in异常 path=" + path, ex);
                }
            }
        }
    }

js代码

通过浏览器进行下载

<a href="/serlvet/dowloadFile">下载</a> 

或者

window.open("/serlvet/dowloadFile")

blob

controller

关键在这响应头:application/octet-stream

protected void download(String path, String fileName) {
        File file = new File(path);
        if (!file.exists()) {
            logger.error("下载的文件模板不存在 path=" + path + ",fileName=" + fileName);
        }
        //下载
        OutputStream out = null;
        BufferedInputStream in = null;
        try {
            getResponse().setCharacterEncoding("UTF-8");
            getResponse().setContentType("application/octet-stream");
            getResponse().setHeader("Content-Disposition", "attachment; filename=" + fileName);
            out = getResponse().getOutputStream();
            in = new BufferedInputStream(new FileInputStream(path));
            int line;
            while ((line = in.read()) != -1) {
                out.write(line);
            }
        } catch (Exception ex) {
            logger.error("下载文件失败 path=" + path, ex);
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (Exception ex) {
                    logger.error("关闭out异常 path=" + path, ex);
                }
            }
            if (null != in) {
                try {
                    in.close();
                } catch (Exception ex) {
                    logger.error("关闭in异常 path=" + path, ex);
                }
            }
        }
    }

js代码[引用博客]

// 通过后端接口下载文件
function downloadFile() {
  // 发起Ajax请求获取文件数据
  $.ajax({
    url: '/download',
    type: 'GET',
    dataType: 'binary',
    success: function(response) {
      // 创建Blob对象
      var blob = new Blob([response]);

      // 创建URL对象
      var url = URL.createObjectURL(blob);

      // 创建a标签并设置相关属性
      var link = document.createElement('a');
      link.href = url;
      link.download = 'file.txt';

      // 触发点击事件进行下载
      link.click();

      // 释放URL对象
      URL.revokeObjectURL(url);
    }
  });
}

json

controller

public Result execute() throws Exception {
		Result result = new Result();
		result.setErr_no(0);
		try {
			String xlsBase64 = xlsToBase64("文件绝对路径");
			DataRow dr = new DataRow();
			dr.set("fileName",param.getFileName()+".xlsx");
			dr.set("fileBase64Str",xlsBase64);
			result.setResult(dr);
		}catch (Exception ex){
			result.setErr_no(-99);
			result.setErr_info("系统错误");
			logger.error("下载异常", ex);
		}
		return result;
}

protected  String xlsToBase64(String path){
        File file = new File(path);
        if (!file.exists()) {
            logger.error("下载的文件不存在 path=" + path );
            return null;
        }
        try{
            return Base64Util.encodeBase64String(FileUtils.readFileToByteArray(file));
        }catch (Exception e){
            logger.error("文件转Base64失败 path=" + path, e);
        }
        return null;
    }

javascript 【引用博客】

var raw = window.atob(data.result.fileBase64Str);
var uInt8Array = new Uint8Array(raw.length);
for (var i = 0; i < raw.length; i++) {
  uInt8Array[i] = raw.charCodeAt(i);
}

const link = document.createElement("a");
const blob = new Blob([uInt8Array],{
   type: 'application/vnd.ms-excel'
})

link.style.display = 'none';
link.href = URL.createObjectURL(blob);
link.setAttribute('download',data.result.fileName+'.xls');

document.body.appendChild(link)
link.click()

document.body.removeChild(link)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值