java 下载网络图片输入到浏览器进行下载

编程入门 行业动态 更新时间:2024-10-20 09:25:26

java 下载网络图片输入到浏览器<a href=https://www.elefans.com/category/jswz/34/1711648.html style=进行下载"/>

java 下载网络图片输入到浏览器进行下载

需求:满足用户,可以在前端下载图片,图片为网络图片

图片链接比如:.thumb.700_0.jpg

 

以下代码标红的地方是关键,由于是浏览器请求,输出流应该从response.getOutputStream(); 中获得

 

前端代码:

 

<a id="QrCodeDownload" href="<%=path%>/base/ssCheckPoint/downImg?src=.thumb.700_0.jpg" download="二维码"><span>下载图片</span></a>

后端代码:
 

public static void main(String[] args) throws Exception {String imgPath =".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();}}

 

更多推荐

java 下载网络图片输入到浏览器进行下载

本文发布于:2024-03-23 18:09:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1741225.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:进行下载   浏览器   图片   网络   java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!