后台根据url下载文件

//前端代码:

<a href="<%=basePath %>bgApply/download?url=${url}" title="约谈附件">下载</a>

//后台根据前台提交的url地址进行文件下载

后端代码:

@RequestMapping("/download")
    public void downLoad(HttpServletRequest request, HttpServletResponse response, String url)
            throws IOException {
        int i = url.lastIndexOf("/");
        String fileName = url.substring(i + 1);
        URL ul = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) ul.openConnection();
        conn.setConnectTimeout(3 * 1000);
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        InputStream inputStream = conn.getInputStream();
        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();
        byte[] bs =  bos.toByteArray();
        response.setContentType("application/octet-stream;charset=ISO8859-1");
        BufferedOutputStream output = null;
        BufferedInputStream input = null;    
        try {
            output = new BufferedOutputStream(response.getOutputStream());
            String fileNameDown = new String(fileName.getBytes(), "ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileNameDown);
            output.write(bs);
            response.flushBuffer();    
        } catch (Exception e) {
            }
        finally {
            if (input != null)
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (output != null)
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }

猜你喜欢

转载自blog.csdn.net/gzkahjl/article/details/81533808
今日推荐