java 根据URL 下载文件

1、废话不多说,如下图所示

    @ApiOperation("文件下载")
    @GetMapping("/download")
    public void download(@RequestParam("fileUrl") String fileUrl, @RequestParam("fileName") String fileName, HttpServletResponse response) throws IOException {
        log.info("download--fileUrl: {},fileName: {}",fileUrl,fileName);

        InputStream download = null;
        ServletOutputStream outputStream = null;
        try{
            URL url = new URL(fileUrl);
            // HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            // connection.setConnectTimeout(5*1000);
            // connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            // download = connection.getInputStream();
            download = url.openStream();

            response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            response.addHeader("charset", "utf-8");
            response.addHeader("Pragma", "no-cache");
            String encodeName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
            response.addHeader("content-disposition", "attachment;fileName="+encodeName);
            outputStream = response.getOutputStream();
            outputStream.write(IOUtils.toByteArray(download));

        }catch (Exception e){
            log.error("文件下载失败",e);

        }finally{
            if(download != null){
                download.close();
            }
            if(outputStream != null){
                outputStream.close();
            }
        }
    }
posted @ 2023-05-05 14:58  吴川华仔博客  阅读(1166)  评论(0编辑  收藏  举报