java外部图片下载

@RequestMapping("/downloadImg")
private static void downloadImg(String imgUrl,HttpServletRequest request, HttpServletResponse response) throws Exception {
    URL url =new URL(imgUrl);
    InputStream inStream = url.openConnection().getInputStream();//通过输入流获取图片数据
    byte[] btImg = readInputStream(inStream);//得到图片的二进制数据

    response.setHeader("Content-Type","application/octet-stream");
    response.setHeader("Content-Disposition","attachment;filename=gaga.jpg");
    response.getOutputStream().write(btImg);
    response.getOutputStream().flush();
    response.getOutputStream().close();
}

/**
 * 从输入流中获取数据
 * @param inStream 输入流
 * @return
 * @throws Exception
 */
public static byte[] readInputStream(InputStream inStream) throws Exception{
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len = 0;
    while( (len=inStream.read(buffer)) != -1 ){
        outStream.write(buffer, 0, len);
    }
    inStream.close();
    return outStream.toByteArray();
}

你可能感兴趣的:(java外部图片下载)