需求:满足用户,可以在前端下载图片,图片为网络图片
图片链接比如:http://img4.duitang.com/uploads/item/201201/07/20120107154546_Cxzk8.thumb.700_0.jpg
以下代码标红的地方是关键,由于是浏览器请求,输出流应该从response.getOutputStream(); 中获得
前端代码:
<a id="QrCodeDownload" href="<%=path%>/base/ssCheckPoint/downImg?src=http://img4.duitang.com/uploads/item/201201/07/20120107154546_Cxzk8.thumb.700_0.jpg" download="二维码"><span>下载图片</span></a>
后端代码:
public static void main(String[] args) throws Exception { String imgPath ="http://img4.duitang.com/uploads/item/201201/07/20120107154546_Cxzk8.thumb.700_0.jpg"; downNetWorkImgUtil(null,imgPath); //注意,此处其实不能为null,只是在main方法中给大家举例一下调用的方式,这里应该要传response }
/** * TODO: 下载网络图片(文件流输出到浏览器弹出下载) * * @param: * @return: * @auther: mukk * @date: 2019/9/5 17:39 */ public static void downNetWorkImgUtil(HttpServletResponse response, String imgPath) throws Exception { try { URL url = new URL(imgPath); DataInputStream dataInputStream = new DataInputStream(url.openStream()); OutputStream fileOutputStream = response.getOutputStream(); ByteArrayOutputStream output = new ByteArrayOutputStream(); response.reset(); response.setContentType("application/octet-stream"); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-disposition", "attachment; filename=" + (imgPath.substring(imgPath.lastIndexOf("/") + 1, imgPath.length()))); byte[] buffer = new byte[1024]; int length; while ((length = dataInputStream.read(buffer)) > 0) { output.write(buffer, 0, length); } byte[] context = output.toByteArray(); fileOutputStream.write(output.toByteArray()); dataInputStream.close(); fileOutputStream.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }