java工具类 - 与前端交互文件转流

@Slf4j
public class FileUtil {
 /**
     * 文件转流
     * @param file
     * @param fileName
     * @param response 
     * @return
     * @throws Exception
     */
    public static Object saveResponseFile(File file, String fileName, HttpServletResponse response, Boolean isInLine) throws Exception {

        setContentType(fileName, response);
        response.setCharacterEncoding("UTF-8");
        String headerType = "attchement";
        if (isInLine != null && isInLine) {
            //"inline"
            headerType = "inline";
        }
        response.setHeader("Content-Disposition", headerType + ";filename=" + URLEncoder.encode(fileName, "UTF-8"));

        OutputStream out = null;

        FileInputStream fis = null;
        try {
            //获取要下载的文件输入流
            fis = new FileInputStream(file);
            int len = 0;
            //通过response对象获取outputStream流
            out = response.getOutputStream();
            byte[] bytes = new byte[1024];
            while ((len = fis.read(bytes)) != -1) {
                out.write(bytes, 0, len);
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        } finally {
            try {
                if (out != null)
                    out.close();
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        return true;
    }

    public static void setContentType(String fileName, HttpServletResponse response) {

        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(Locale.ROOT);
        switch (suffix) {
            case "pdf":
                response.setContentType("application/pdf");
                return;
            case "jpg":
                response.setContentType("image/jpeg");
                return;
            case "png":
                response.setContentType("image/png");
                return;
            default:
                response.setContentType("application/octet-stream");
                return;
        }
    }
   }

== 使用:==
FileUtil.saveResponseFile(new File(resultMap.get(“path”)),resultMap.get(“fileName”),response,false);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值