java从项目中下载文件

controller

    public void downloadMachine() {
        InputStream inputStream = this.getClass().getResourceAsStream("/templates/模板.xlsx");
        String fileName = "模板.xlsx";
        ResponseUtils.exportFile(fileName,inputStream);
    }

工具类 ResponseUtils

package com.imfbp.fls.before.commons.utils;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

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

public class ResponseUtils {

    /**
     * 文件放入Response中
     */
    public static void exportFile(File file) {
        try {
            exportFile(file.getName(),new FileInputStream(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 文件流放入Response中
     */
    public static void exportFile(String fileName,InputStream inputStream) {
        if(StringUtils.isEmpty(fileName)) throw new RuntimeException("文件名称不能为空!");
        if(inputStream == null) throw new RuntimeException("导出文件流不能为空!");
        try {
            //1、获取扩展名
            String ext = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletResponse response = attributes.getResponse();
            response.setCharacterEncoding("utf-8");
            String name = URLEncoder.encode(StringUtils.isEmpty(fileName)?fileName:fileName.substring(0,fileName.length()-ext.length()-1), "utf-8");
            response.setHeader("filename", name);
            response.setHeader("Access-Control-Expose-Headers", "filename");

            response.resetBuffer();
            response.setContentType("utf-8");
            response.setHeader("content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"),"ISO8859-1"));
            String mimeType = getMimeType(ext);
            if(StringUtils.isEmpty(mimeType)) {
                response.setContentType("applicationnd.openxmlformats-officedocument.spreadsheetml.sheet");
            } else {
                response.setContentType(mimeType);
            }
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            bis.close();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 文档类型容器
     */
    private final static Map mimeTypeMap = new HashedMap();

    static {
        mimeTypeMap.put("doc", "application/msword");
        mimeTypeMap.put("dot", "application/msword");
        mimeTypeMap.put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        mimeTypeMap.put("dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template");
        mimeTypeMap.put("docm", "application/vnd.ms-word.document.macroEnabled.12");
        mimeTypeMap.put("dotm", "application/vnd.ms-word.template.macroEnabled.12");
        mimeTypeMap.put("xls", "application/vnd.ms-excel");
        mimeTypeMap.put("xlt", "application/vnd.ms-excel");
        mimeTypeMap.put("xla", "application/vnd.ms-excel");
        mimeTypeMap.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        mimeTypeMap.put("xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template");
        mimeTypeMap.put("xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12");
        mimeTypeMap.put("xltm", "application/vnd.ms-excel.template.macroEnabled.12");
        mimeTypeMap.put("xlam", "application/vnd.ms-excel.addin.macroEnabled.12");
        mimeTypeMap.put("xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12");
        mimeTypeMap.put("ppt", "application/vnd.ms-powerpoint");
        mimeTypeMap.put("pot", "application/vnd.ms-powerpoint");
        mimeTypeMap.put("pps", "application/vnd.ms-powerpoint");
        mimeTypeMap.put("ppa", "application/vnd.ms-powerpoint");
        mimeTypeMap.put("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
        mimeTypeMap.put("potx", "application/vnd.openxmlformats-officedocument.presentationml.template");
        mimeTypeMap.put("ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow");
        mimeTypeMap.put("ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12");
        mimeTypeMap.put("pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12");
        mimeTypeMap.put("potm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12");
        mimeTypeMap.put("ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12");
        mimeTypeMap.put("pdf", "application/pdf");
        mimeTypeMap.put("m4a", "audio/*");
        mimeTypeMap.put("mp3", "audio/*");
        mimeTypeMap.put("mid", "audio/*");
        mimeTypeMap.put("xmf", "audio/*");
        mimeTypeMap.put("ogg", "audio/*");
        mimeTypeMap.put("wav", "audio/*");
        mimeTypeMap.put("3gp", "video/*");
        mimeTypeMap.put("mp4", "video/*");
        mimeTypeMap.put("apk", "application/vnd.android.package-archive");
        mimeTypeMap.put("pptx", "application/vnd.ms-powerpoint");
        mimeTypeMap.put("js", "application/x-javascript");
        mimeTypeMap.put("zip", "application/zip");
        mimeTypeMap.put("gif", "image/gif");
        mimeTypeMap.put("jpeg", "image/jpeg");
        mimeTypeMap.put("jpg", "image/jpeg");
        mimeTypeMap.put("jpe", "image/jpeg");
        mimeTypeMap.put("png", "image/png");
        mimeTypeMap.put("html", "text/html");
        mimeTypeMap.put("txt", "text/plain");
        mimeTypeMap.put("xml", "text/xml");
    }

    public static String getMimeType(String ext) {
        return mimeTypeMap.get(ext);
    }
}

访问控制层方法即可下载

你可能感兴趣的:(java从项目中下载文件)