Spring MVC 在线文件下载

public ResponseEntity<byte[]> download(String path) throws IOException {
        // 找到对应真实的URL
        String httpUrl = "http://a2.att.hudong.com/36/48/19300001357258133412489354717.jpg";

        URL url = new URL(httpUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 设置超时间为3秒
        conn.setConnectTimeout(3000);
        // 防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        // 得到输入流
        InputStream is = conn.getInputStream();
        byte[] body = readInputStream(is);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", "111.png");
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        // 关闭流
        is.close();
        return new ResponseEntity<>(body, headers, HttpStatus.OK);
    }

猜你喜欢

转载自www.cnblogs.com/houyl/p/12922864.html