ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

文件下载的写法

2021-12-18 11:34:10  阅读:203  来源: 互联网

标签:文件 String resp download new LOGGER null 写法 下载


private void download(String token, String guid, HttpServletRequest req, HttpServletResponse resp) {
        File outputFile = null;
        try {
            EdmConfig config = getEdmConfig(token);
            // 请求参数类
            ExcelTaskRequestVO requestVO = new ExcelTaskRequestVO();

            UserVO user = (UserVO) RequestContext.getCurrent().getUser();
            // 当前用户id
            requestVO.setUserId(String.valueOf(user.getUserId()));
            // 创建人
            requestVO.setCreatedBy(user.getUserAccount());
            // Excel引擎访问地址
            requestVO.setServiceUrl(edmEndPoint);
            // 导出任务的GUID
            requestVO.setGuid(guid);
            EdmExcelClient excelClient = new EdmExcelClient(config);
            int times = 0; // 防止无限循环
            String edmStatus = getEdmStatus(excelClient, requestVO);
            while (times < 10 && !"FINISH".equals(edmStatus)) {
                try {
                    Thread.sleep(500);
                    LOGGER.info("sleep 500 millisecond for download finish");
                } catch (InterruptedException e) {
                    LOGGER.info("sleep download finish InterruptedException:", e);
                }
                times++;
                edmStatus = getEdmStatus(excelClient, requestVO);
            }
            ResponseObject responseObject = excelClient.download(requestVO);
            if (responseObject != null && responseObject.getStatus() == 200) {
                Headers headers = responseObject.getResponseHeaders();
                if (headers == null) {
                    LOGGER.error("-------------------headers == null-------------------");
                    return;
                }
                String contentType = headers.get("Content-Type");
                if ("application/json;charset=UTF-8".equals(contentType)) {
                    LOGGER.debug("do nothing");
                    // JSON反序列化
                } else if ("application/octet-stream;charset=UTF-8".equals(contentType)) {
                    // 方式一:不经过服务器,但是文件名改不了
                    /*
                     * resp.setContentType("application/octet-stream");
                     * String disposition = responseObject.getResponseHeaders().get("Content-Disposition");
                     * Pattern pattern = Pattern.compile("attachment;filename=(.*?)$", Pattern.CASE_INSENSITIVE);
                     * Matcher matcher = pattern.matcher(disposition);
                     * if (matcher.find()) {
                     * String filename = URLDecoder.decode(matcher.group(1), CharsetNames.CS_UTF8);
                     * resp.setHeader("Content-Disposition", "attachment;filename=" + filename);
                     * }
                     * resp.setCharacterEncoding(CharsetNames.CS_UTF8);
                     * InputStream input = responseObject.getByteStream();
                     * OutputStream output = resp.getOutputStream();
                     * StreamUtil.transfer(input, output);
                     */

                    // 方式二:先存到服务器再下载,这个中文文件名会乱码
                    FileInfoVO fileInfoVO = new FileInfoVO();
                    String disposition = responseObject.getResponseHeaders().get("Content-Disposition");
                    Pattern pattern = Pattern.compile("attachment;filename=(.*?)$", Pattern.CASE_INSENSITIVE);
                    if (disposition != null) {
                        Matcher matcher = pattern.matcher(disposition);
                        if (matcher.find()) {
                            String filename = URLDecoder.decode(matcher.group(1), CharsetNames.CS_UTF8);
                            fileInfoVO.setDisplayName(filename);
                            String outputFilePath = System.getProperty("java.io.tmpdir") + filename;
                            String checkOutputFilePath = StringVerifyUtil.dealSpecialChar(outputFilePath);
                            outputFile = new File(checkOutputFilePath);
                            IOUtils.copyTo(responseObject.getByteStream(), outputFile.getCanonicalPath(), 1024);
                            // just for cloud dragon
                            setFileInfoVo(outputFile, fileInfoVO);
                        }
                    }
                    downloadOutput(req, resp, fileInfoVO);
                }
            }
        } catch (EdmException | IOException | DownloadException e) {
            LOGGER.error("download error:", e);
        } finally {
            if (outputFile != null) {
                boolean delFlag = outputFile.delete();
                if (!delFlag) {
                    LOGGER.info("outputFile delete failed");
                }
            }
        }
    }

    private void setFileInfoVo(File outputFile, FileInfoVO fileInfoVo) {
        InputStream in = null;
        try {
            File checkFile = StringVerifyUtil.checkFilePath(outputFile);
            in = new FileInputStream(checkFile);
            final ByteArrayOutputStream baoS = new ByteArrayOutputStream();
            final byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) > -1) {
                baoS.write(buffer, 0, len);
            }
            baoS.flush();

            fileInfoVo.setInputStream(new ByteArrayInputStream(baoS.toByteArray()));
            fileInfoVo.setStream(true);
        } catch (IOException e) {
            LOGGER.info("IOException ", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }
    }

    private void downloadOutput(HttpServletRequest req, HttpServletResponse resp, FileInfoVO file)
        throws DownloadException {
        InputStream in = null;
        OutputStream out = null;
        try {
            // 尝试下载文件
            // 根据浏览器判断下载文件名转义 wx244051 2016-01-14
            String agent = req.getHeader("User-Agent").toLowerCase();

            in = file.getInputStream();
            if (in != null) {
                if (agent.contains("msie") || agent.contains("trident")) {
                    download.outputFromStream(req, resp, in, file.getDisplayName(), true, 0L);
                } else {
                    download.outputFromStream(req, resp, in,
                        new String(file.getDisplayName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1),
                        false, 0L);
                }
            }
        } catch (FileNotFoundException e) {
            LOGGER.error("mkpVerticalPrice file not found -- ", e);
            throw new DownloadException("honor.jalor5.download.support.00010002");
        } catch (Exception e) {
            LOGGER.error("mkpVerticalPrice download error -- ", e);
            throw new DownloadException("honor.jalor5.download.support.00010001");
        } finally {
            StreamUtil.closeStreams(in, out);
        }
    }

 

标签:文件,String,resp,download,new,LOGGER,null,写法,下载
来源: https://www.cnblogs.com/dukedu/p/15704604.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有