java web实现在线文件下载

public static JSONObject downFileByUrl(HttpServletRequest request,HttpServletResponse response,String fileUrl, String fileName){
        OutputStream toClient = null;
        InputStream in = null;
        HttpURLConnection conn = null;
        try {
            URL url = new URL(fileUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Connection","Keep-Alive");
            // conn.connect();
            int responseCode = conn.getResponseCode();
            if(responseCode != HttpURLConnection.HTTP_OK){
                return RespMsg.FAIL("链接不可用,请检查链接有效性");
            }

            int length = conn.getContentLength();
            in = conn.getInputStream();

            String userAgent = request.getHeader("USER-AGENT");
            if (org.apache.commons.lang.StringUtils.contains(userAgent, "MSIE")) {//IE浏览器
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else if (org.apache.commons.lang.StringUtils.contains(userAgent, "Mozilla")) {//google,火狐浏览器
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "UTF-8");//其他浏览器
            }
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Content-Length", "" + length);
            toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            byte[] buff = new byte[1024];
            while (true) {
                int read = in.read(buff);
                if (read == -1)
                    break;
                toClient.write(buff, 0, read);
            }
            toClient.flush();
            return RespMsg.SUCCESS();
        } catch (Exception e) {
            e.printStackTrace();
            return RespMsg.FAIL("链接不可用,请检查链接有效性");
        } finally {
            try {
                if (toClient != null) {
                    IOUtils.closeQuietly(toClient);
                    toClient.close();
                }
                if (in != null) {
                    IOUtils.closeQuietly(in);
                    in.close();
                }
               // conn.disconnect();
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/u013045878/article/details/81392701
今日推荐