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);
    }


/**
* 从输入流中获取字节数组
* @param inputStream
* @return
* @throws IOException
*/
private byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
 

 

posted @ 2020-05-20 12:18  悟空为师想要吃肉  阅读(101)  评论(0)    收藏  举报