springboot下载本地文件

springboot项目

package com.hirebigdata.datamanage.sentiment.controller.joinDepotManage;

import com.hireBigData.common.util.CommonUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @Auther: LH
 * @Date: 2019/03/05 18:01
 * @Description:
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @javax.annotation.Resource
    private ResourceLoader resourceLoader;


    /**
     * 本地下载文件excel模板
     * @param response
     * @param request
     */
    @RequestMapping("/downTemplate")
    public void downloadTemplate(HttpServletResponse response, HttpServletRequest request){
        InputStream inputStream = null;
        ServletOutputStream servletOutputStream = null;

        try{
            String fileName = "";
            String path = "";
            path = "/template/舆情批量导入模板.xlsx";
            fileName = "舆情批量导入模板.xlsx";

            if (CommonUtil.isNotEmpty(path)){
                Resource resource = resourceLoader.getResource("classpath:" + path);
                response.setContentType("application/vnd.ms-excel");
                response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
                response.addHeader("charset", "utf-8");
                response.addHeader("Pragma", "no-cache");
                String encodeName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
                response.setHeader("Content-Disposition", "attachment; filename=\"" + encodeName + "\"; filename*=utf-8''" + encodeName);
                inputStream = resource.getInputStream();
                servletOutputStream = response.getOutputStream();
                IOUtils.copy(inputStream, servletOutputStream);
                response.flushBuffer();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (servletOutputStream != null) {
                    servletOutputStream.close();
                    servletOutputStream = null;
                }
                if (inputStream != null) {
                    inputStream.close();
                    inputStream = null;
                }
                // 召唤jvm的垃圾回收器
                System.gc();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

}

你可能感兴趣的:(springboot下载本地文件)