Java下载文件通过URL

public void downFile(HttpServletResponse response, String url) {
    if (null == url || "".equals(url)){
        return new ErrorEntity(PARAMETER_ERROR_CODE, PARAMETER_ERROR_MESSAGE);
    }
    /*File file = new File(url);*/
    response.setHeader("content-type", "application/octet-stream");
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment;filename=" + url);
    byte[] buff = new byte[1024];
    BufferedInputStream bis = null;
    OutputStream os;
    try {
        os = response.getOutputStream();
        bis = new BufferedInputStream(new FileInputStream(new File(url)));
        int i = bis.read(buff);
        while (i != -1) {
            os.write(buff, 0, buff.length);
            os.flush();
            i = bis.read(buff);
        }
    } catch (FileNotFoundException e){
        return new ErrorEntity(501, "FileNotFoundException:"+e.getMessage());
    } catch (IOException e) {
        return new ErrorEntity(501, "IOException:"+e.getMessage());
    } finally {
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

你可能感兴趣的:(Java下载文件通过URL)