rinoa1023

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

使用springboot的restTemplate.exchange实现文件下载

目录结构:

1. application.properties配置文件

demo项目: 下载接口调用方

server.port=8081
server.servlet.context-path=/demo

# http连接超时时间设置
system.http.readTimeout=720
system.http.connectTimeout=720

demo1项目: 下载接口提供方

server.port=8082
server.servlet.context-path=/demo1

2. RestTemplate配置

@Configuration
public class RestTemplateConfig {
    /**
     * 秒转换为毫秒的单位
     */
    private static final int MILLISECOND_UNIT = 1000;

    /**
     * http连接的读取超时时间
     */
    @Value("${system.http.readTimeout}")
    private int httpReadTimeout;

    /**
     * http连接的超时时间
     */
    @Value("${system.http.connectTimeout}")
    private int httpConnectTimeout;


    @Bean
    public RestTemplate restTemplate() {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setReadTimeout(httpReadTimeout * MILLISECOND_UNIT);
        requestFactory.setConnectTimeout(httpConnectTimeout * MILLISECOND_UNIT);

        return new RestTemplate(requestFactory);
    }
}

3. 下载文件

restTemplate.exchange 调用demo2项目的 downloadFile 接口, 结果保存在e盘目录下

@Service
public class DownloadService {

    @Autowired
    private RestTemplate restTemplate;

    public void downloadFile() {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);

        String content = new Gson().toJson("");
        HttpEntity<String> entity = new HttpEntity<String>(content, headers);

        try {
            ResponseEntity<byte[]> bytes = restTemplate.exchange("http://127.0.0.1:8082/demo1/downloadFile", HttpMethod.POST, entity, byte[].class);
            String productZipName = "test111.zip";
            String path = "E:\\";
            File f = new File("E:\\" + productZipName);
            if (!f.exists()) {
                try {
                    f.createNewFile();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            try (FileOutputStream out = new FileOutputStream(f);) {
                out.write(bytes.getBody(), 0, bytes.getBody().length);
                out.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
            UploadUtil.unZip(f, path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

4. 调用工具方法

public class UploadUtil {

    public static void unZip(File srcFile, String destDirPath) throws RuntimeException {
        long start = System.currentTimeMillis();
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
        }
        // 开始解压
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(srcFile, Charset.forName("gbk"));
            Enumeration<?> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                System.out.println("解压" + entry.getName());
                // 如果是文件夹,就创建个文件夹
                if (entry.isDirectory()) {
                    String dirPath = destDirPath + "/" + entry.getName();
                    File dir = new File(dirPath);
                    dir.mkdirs();
                } else {
                    // 如果是文件,就先创建一个文件,然后用io流把内容copy过去
                    File targetFile = new File(destDirPath + "/" + entry.getName());
                    // 保证这个文件的父文件夹必须要存在
                    if (!targetFile.getParentFile().exists()) {
                        targetFile.getParentFile().mkdirs();
                    }
                    targetFile.createNewFile();
                    // 将压缩文件内容写入到这个文件中
                    InputStream is = zipFile.getInputStream(entry);
                    FileOutputStream fos = new FileOutputStream(targetFile);
                    int len;
                    byte[] buf = new byte[1024];
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    // 关流顺序,先打开的后关闭
                    fos.close();
                    is.close();
                }
            }
            long end = System.currentTimeMillis();
            System.out.println("解压完成,耗时:" + (end - start) + " ms");
        } catch (Exception e) {
            throw new RuntimeException("unzip error from ZipUtils", e);
        } finally {
            if (zipFile != null) {
                try {
                    zipFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

5. 被调用方, controller

@RestController
public class DownloadController {

    @Autowired
    private DownloadService downloadService;

    @PostMapping("downloadFile")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response) {
        downloadService.downloadFile(request, response);
    }

}

6. 被调用方, service

下载d盘下的 test.zip 

@Log
@Service
public class DownloadService {

    private static final int ZIP_BUFFER_SIZE = 8192;

    public void downloadFile(HttpServletRequest request, HttpServletResponse response) {
        try {
            String zipFileName = "test.zip";
            File file = new File("D:\\test.zip");
            if (!file.exists()) {
                log.info("下载的软件包不存在 " + file.getPath());
                return;
            }
            try (InputStream ins = new FileInputStream("D:\\test.zip");
                 BufferedInputStream bins = new BufferedInputStream(ins);
                 OutputStream outs = response.getOutputStream();
                 BufferedOutputStream bouts = new BufferedOutputStream(outs)) {
                response.setContentType("application/x-download");
                response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(zipFileName, "UTF-8"));
                int bytesRead = 0;
                byte[] buffer = new byte[ZIP_BUFFER_SIZE];
                while ((bytesRead = bins.read(buffer, 0, ZIP_BUFFER_SIZE)) != -1) {
                    bouts.write(buffer, 0, bytesRead);
                }
                bouts.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

 

posted on 2021-08-30 14:41  rinoa1023  阅读(3063)  评论(0编辑  收藏  举报