weixin_43490664 2019-03-12 08:21 采纳率: 100%
浏览 1403
已采纳

写一个controller service,下载springboot项目中的resource下的upload文件夹下的load.txt

写一个controller service,下载springboot项目中的resource下的upload文件夹下的load.txt,本人之前没接触过,谢谢大牛写的详细点!!!

  • 写回答

2条回答 默认 最新

  • TinerSky 2019-03-12 08:59
    关注

    这个题的有两个难点:
    1、读取资源文件,下载文件;
    2、spring boot controller service的写法。

    一、Controller Service代码如下:

    package com.qianqiangongzi.controller;
    
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.qianqiangongzi.utils.DownloadResourceFileUtils;
    
    /**
     * 下载资源文件接口
     * 
     * @author 谦谦公子爱编程
     *
     */
    @RestController
    @RequestMapping(value = "/api/DownloadResourceFile")
    public class DownloadResourceFileController {
    
        /**
         * 下载资源文件
         * 
         * @param response
         * @throws Exception
         */
        @RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
        public void downloadFile(HttpServletResponse response) throws Exception {
            DownloadResourceFileUtils.downloadFile(response);
        }
    }
    
    

    二、下载文件工具类

    package com.qianqiangongzi.utils;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.InputStream;
    import java.io.OutputStream;
    
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.lang3.exception.ExceptionUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.util.ResourceUtils;
    
    /**
     * 下载资源文件
     * 
     * @author 谦谦公子爱编程
     *
     */
    public class DownloadResourceFileUtils {
        public static final String INLINE = "inline"; // 在线打开
        public static final String ATTACHMENT = "attachment"; // 附件下载
    
        public static final Logger logger = LoggerFactory.getLogger(DownloadResourceFileUtils.class);
    
        public static void downloadFile(HttpServletResponse response) throws Exception {
            // 下载文件部分路径
            String fileName = "upload\\load.txt";
            // 获取文件根路径
            String basePath = getResourceBasePath();
            // 获取文件路径
            File downloadFile = new File(basePath, fileName);
            // 下载问价
            downloadFile(response, downloadFile.getAbsolutePath(), downloadFile.getName(), ATTACHMENT);
        }
    
        /**
         * 获取项目根路径
         * 
         * @return
         */
        private static String getResourceBasePath() {
            // 获取跟目录
            File path = null;
            try {
                path = new File(ResourceUtils.getURL("classpath:").getPath());
            } catch (FileNotFoundException e) {
                // nothing to do
            }
            if (path == null || !path.exists()) {
                path = new File("");
            }
    
            String pathStr = path.getAbsolutePath();
            // 如果是在eclipse中运行,则和target同级目录,如果是jar部署到服务器,则默认和jar包同级
            pathStr = pathStr.replace("\\target\\classes", "");
            pathStr += "\\src\\main\\resources";
    
            return pathStr;
        }
    
        /*
         * 下载文件,需要文件绝对路径
         * 
         * @param response 写回流对象
         * 
         * @param filePath 文件的绝对路径
         * 
         * @param fileName 下载时的文件名称
         * 
         * @param downloadWay 下载方式INLINE(在线打开) or ATTACHMENT(附件下载)
         * 
         * @throws Exception
         */
        private static void downloadFile(HttpServletResponse response, String filePath, String fileName, String downloadWay)
                throws Exception {
            try {
                response.addHeader("Content-Disposition", downloadWay + "; filename=" + fileName);
                InputStream is = new FileInputStream(filePath);
                byte[] b = new byte[8 * 1024];
                int length = -1;
                OutputStream out = response.getOutputStream();
                while ((length = is.read(b)) != -1) {
                    out.write(b, 0, length);// 输出
                }
                out.close();
                is.close();
            } catch (Exception e) {
                if (logger.isErrorEnabled()) {
                    logger.error(ExceptionUtils.getMessage(e));
                }
                throw e;
            }
        }
    }
    
    

    经过测试,没有任何问题:
    浏览器输入下载地址:
    http://localhost:8088/api/DownloadResourceFile/downloadFile

    资源文件

    下载文件

    编码不易,望采纳!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题