SpringBoot 下载文件

下载文件  SpringBoot 接口输出文件流 & Vue 下载文件流,获取 Header 中的文件名

@SpringBootTest
class DownloadTests {
    Logger logger = LoggerFactory.getLogger(this.getClass());
    
    CountDownLatch countDownLatch;

    @Test
    void downloadApi() throws InterruptedException {
        for (int i = 1; i < 10; i++) {
            int idx = i;
            new Thread(() -> logger.info(download("http://www.vipsoft.com.cn/api/download", idx + ".zip"))).start();
        }
        
        countDownLatch = new CountDownLatch(count);
        countDownLatch.await();
    }


    public String download(String downloadUrl, String saveName) {
        String result = "";
        // 下载网络文件
        int bytesum = 0;
        int byteread = 0;
        FileOutputStream fs = null;
        InputStream inStream = null;
        try {
            logger.info("下载地址 => {}", downloadUrl);
            URL url = new URL(downloadUrl);
            URLConnection conn = url.openConnection();
            inStream = conn.getInputStream();
            String savePath = StrUtil.format("{}/{}", "D:\\temp", saveName);
            fs = new FileOutputStream(savePath);
            byte[] buffer = new byte[1204];
            int length;
            while ((byteread = inStream.read(buffer)) != -1) {
                fs.write(buffer, 0, byteread);
                bytesum += byteread;
                if (bytesum % (1024 * 1024) < 1000) {
                    System.out.println(Thread.currentThread().getName() + " " + saveName + " 已写入(M) " + (bytesum / 1024 / 1024));
                }
            }
            fs.flush();
            result = StrUtil.format("{}/{}", "D:\\temp", saveName);
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage(), e);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            IoUtil.close(inStream);
            IoUtil.close(fs);
            countDownLatch.countDown();
        }
        return result;
    }
}

 

posted @ 2022-10-09 13:46  VipSoft  阅读(944)  评论(0编辑  收藏  举报