HttpURLConnection 下载文件

            String fileUrl = request.getRequestURL().substring(0,
                    request.getRequestURL().indexOf("/rest"))
                    + "/test/resources/images/template.jpg";
            URL url = new URL(fileUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            response.reset();
            response.setContentType("application/x-msdownload");
            response.addHeader("Content-Disposition", "attachment; filename="
                    + new String("template.jpg".getBytes("gbk"), "iso-8859-1"));
            OutputStream os = response.getOutputStream();
            InputStream in = conn.getInputStream();
            byte[] b = new byte[1024];
            int r = 0;
            while ((r = in.read(b)) != -1) {
                os.write(b, 0, r);
            }
            os.flush();
            os.close();
            in.close();
            conn.disconnect();

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。