URL下载文件流

1,406 阅读1分钟

需求:通过URL地址从服务器上将文件以流的形式下载

实现

/* 
* 将文件名与文件类型截取出来 
*/ 
int endIndex = reqmtAtment.getAtmtName().lastIndexOf("."); 
String type= reqmtAtment.getAtmtName().substring(endIndex); 
String name = reqmtAtment.getAtmtName().substring(0, endIndex);
/* 
* 设置传输格式,以及响应头格式 
*/ 
response.setContentType("application/octet-stream;charset=UTF-8"); 
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-Disposition", "attachment;filename="+fileName+type);
/* 
* 通过InputStream将文件读入byte[]数组中,再通过outputStream.write写出byte数组
*/

public InputStream getInputStreamByUrl(String strUrl) {
    HttpsURLConnection conn = null;
    try {
        URL url = new URL(strUrl);
        conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(20 * 1000);
        final ByteArrayOutputStream output = new ByteArrayOutputStream();
        IOUtils.copy(conn.getInputStream(), output);
        return new ByteArrayInputStream(output.toByteArray());
    } catch (Exception e) {
        logger.error("getInputStreamByUrl 异常,exception is {}", e);
    } finally {
        try {
            if (conn != null) {
                conn.disconnect();
            }
        } catch (Exception e) {
        }
    }
    return null;
}

整体样例

/**
 * 根据附件ID下载附件
 * @return
 */
public String downloadById(HttpServletResponse response, String atmtId) {
    ReqmtAtment reqmtAtment = reqmtAtmentExtMapper.selectById(atmtId);
    int endIndex = reqmtAtment.getAtmtName().lastIndexOf(".");
    String type= reqmtAtment.getAtmtName().substring(endIndex);
    String name = reqmtAtment.getAtmtName().substring(0, endIndex);
    response.setContentType("application/octet-stream;charset=UTF-8");
    response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
    String fileName = null;
    try {
        fileName = new String(name.getBytes(),"UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    response.setHeader("Content-Disposition", "attachment;filename="+fileName+type);

    InputStream is = getInputStreamByUrl(reqmtAtment.getAtmtUrl());
    OutputStream os = null;
    try {
        os = response.getOutputStream();
        byte[] b = new byte[1024];
        int len = 0;
        while ((len = is.read(b)) > 0){
            os.write(b, 0 , len);
        }
        os.flush();
    } catch (IOException e) {
        return RdfaResult.fail("400", "获取文件失败");
    }finally {
        if (is!=null){
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (os !=null){
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    return "下载成功";
}

public InputStream getInputStreamByUrl(String strUrl) {
    HttpsURLConnection conn = null;
    try {
        URL url = new URL(strUrl);
        conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(20 * 1000);
        final ByteArrayOutputStream output = new ByteArrayOutputStream();
        IOUtils.copy(conn.getInputStream(), output);
        return new ByteArrayInputStream(output.toByteArray());
    } catch (Exception e) {
        logger.error("getInputStreamByUrl 异常,exception is {}", e);
    } finally {
        try {
            if (conn != null) {
                conn.disconnect();
            }
        } catch (Exception e) {
        }
    }
    return null;
}