相关文章推荐
高大的春卷  ·  jsp ...·  2 周前    · 
空虚的枕头  ·  JSP ...·  1 周前    · 
寂寞的牛肉面  ·  使用ByteBuffer ...·  1 年前    · 
坚强的大象  ·  freemarker中的if...elsei ...·  1 年前    · 



目录

  • 一、最终代码
  • 二、注意点
  • 1、使用Get请求
  • 2、Json文件名乱码问题
  • 3、没有以文件的形式下载


一、最终代码

@GetMapping("/export/{identifier}")    
    public void export(HttpServletResponse response,
                       @PathVariable("identifier") String identifier) throws IOException {
        // 当需要把数据库的某条数据查询出来后,将某个字段存储的值以Json文件的形式返回
        // 前端调用接口时,直接就下载这个Json文件
        // 1.从数据库查询信息
        DataProduct dataProduct = dataProductService.findOneDataProduct(identifier);
        String name = dataProduct.getName();
        // 2.将返回信息格式化为Json字符串
        String formatData = JSONUtil.formatJsonStr(dataProduct.getData());
		// 3.拼接响应头,返回文件名字等信息
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        // 下载文件能正常显示中文
        response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode(name + ".json", "UTF-8"));
        // 4.文件下载
        int len;
        byte[] buffer = new byte[1024];
        try (InputStream in = new ByteArrayInputStream(formatData.getBytes());
             BufferedInputStream bis = new BufferedInputStream(in);
             OutputStream out = response.getOutputStream()) {
            while ((len = bis.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            out.flush();
    }

此时当 前端直接在浏览器地址栏调用此接口(http://ip:port/xxx/export/123456),直接就会返回以.json结尾的json文件。

二、注意点

以上代码有以下注意点

1、使用Get请求

为了能够更直观的展示下载功能,所以使用Get请求,直接在浏览器地址栏输入接口地址访问即可;不需要采用Postman或者Swagger等的方式进行访问。

2、Json文件名乱码问题

使用以下方式能够避免文件名乱码的问题

response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(name + ".json", "UTF-8"));

即 URLEncoder.encode(name + “.json”, “UTF-8”)

3、没有以文件的形式下载

HttpServletResponse的处理必须在文件流的处理前面 ,否则不会以Json文件的形式返回,而是以页面的方式展示Json文件的内容