Home >Java >javaTutorial >Detailed explanation of how to download and open Java web page attachments and images
The following editor will bring you a javaweb page attachment, picturedownload and open (implementation method). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.
I wrote a link to the image in javaweb, which can be opened for preview and also provides a download function.
The following is the preview code, there is nothing to say; if the href is connected to a compressed package file that cannot be opened directly, you can download it directly;
<a target="_blank" class="media" href="img/XD201607000023.gif" rel="external nofollow" rel="external nofollow" >预览</a>
The key is how to download this on the page Picture, so I wrote the following jspUsing a stream to read the file;
<a target="_blank" href="downloadFile.jsp?path=img/&pdfName=aa.gif" rel="external nofollow" >下载</a>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ page language="java" import="java.io.*;" %> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; String classPath = (String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))).replaceAll("file:/", "").replaceAll("%20", " ").trim(); %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <% //得到文件名字和路径 String filepath = request.getParameter("path"); String filename = request.getParameter("pdfName"); //设置响应头和下载保存的文件名 response.setContentType("APPLICATION/OCTET-STREAM"); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); //打开指定文件的流信息 OutputStream outputStream = response.getOutputStream(); InputStream inputStream = new FileInputStream(filepath+filename); byte[] buffer = new byte[1024]; int i = -1; while ((i = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, i); } outputStream.flush(); outputStream.close(); inputStream.close(); outputStream = null; out.clear(); out = pageContext.pushBody(); %> </head> <body> </body> </html>
Finally, I checked the information and found that it is provided in HTML5 Download attribute is added. As long as this attribute is written, the image can be downloaded directly instead of opened directly. Unfortunately, it only supports h5, otherwise it will save trouble.
<a target="_blank" download="aa" href="img/XD201607000023.gif" rel="external nofollow" rel="external nofollow" download="aa" >下载</a>
Download is the file name of the downloaded file.
The above is the detailed content of Detailed explanation of how to download and open Java web page attachments and images. For more information, please follow other related articles on the PHP Chinese website!