後臺根據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();
                }
        }
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章