使用java实现文档下载(通用方法)

  1. 现在大部分的业务都是需要通过后端下载一些模板,又或者在线浏览的,比例word,excel,pdf文件,都是需要下载,所以这里我也是遇到了,本来是在前端写一个链接,直接下载的,但是以防万一,可以通过后端接口对文档进行下载,下面给出代码例子
  2. 这里就写一个controller方法,就没有对他进行二次封装了,完全是copy下来的,如果有人看不习惯,可以对他进行二次封装,把他封装成一个工具类
package com.ruoyi.web.controller.ucase;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

/**
 * 
 * @author Mr.zhou
 * 公共的controller
 * 
 * @Description:下载Controller
 * @Author:Mr.zhou
 * @Date:2022/07/15
 */
@RestController
@RequestMapping("/ucase/download")
@Slf4j
public class UcasePubController {

    //文件所在的目录
    private static final String FIXED_PATH = "static/documentation/";

    private static final String USER_AGENT_MSIE = "MSIE";

    private static final String USER_AGENT_TRIDENT = "Trident";

    @RequestMapping("/template")
    @ResponseBody
    public void downloadTemplate(@RequestParam Map<String, String> params, HttpServletResponse response, HttpServletRequest request) throws IOException {
        log.debug("DownloadController{}==>downloadTemplate()");
        InputStream inputStream = null;
        OutputStream os = null;
        try {
            String path = Thread.currentThread().getContextClassLoader()
                    .getResource("").getPath() + FIXED_PATH + params.get("fileName");
            inputStream = new FileInputStream(new File(path));
            //假如以中文名下载的话,设置下载文件名称
            String filename = params.get("fileName");
            // 针对IE或者以IE为内核的浏览器:
            String userAgent = request.getHeader("User-Agent");
            if (userAgent.contains(USER_AGENT_MSIE) || userAgent.contains(USER_AGENT_TRIDENT)) {
                filename = java.net.URLEncoder.encode(filename, "UTF-8");
            } else {
                // 非IE浏览器的处理:
                filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
            }
            //设置文件下载头
            response.addHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", filename));
            //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("UTF-8");
            os = response.getOutputStream();
            byte[] b = new byte[2048];
            int len;
            while ((len = inputStream.read(b)) > 0) {
                os.write(b, 0, len);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
            }
        }
    }
}

  1. 把文件放在本地的静态资源目录下
    在这里插入图片描述
  2. 通过访问本地链接就可以进行访问了:http://localhost:9999/122/ucase/download/template?fileName=document.docx 参数是你的文件名
  3. 如图
    在这里插入图片描述
  4. 后面我会自己把他封装成一个工具类
  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_46855885

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值