在javaweb中写了一个图片的链接,可以打开预览,另外提供一个下载功能。
以下是预览代码,没什么好说的;href若连接的是一个压缩包文件之类无法直接打开的就可以直接下载;
1
|
< a target = "_blank" class = "media" href = "img/XD201607000023.gif" rel = "external nofollow" rel = "external nofollow" >预览</ a > |
关键在于如何在页面上下载这个张图片,于是写了下面的一个jsp用流来读取文件;
1
|
< a target = "_blank" href = "downloadFile.jsp?path=img/&pdfName=aa.gif" rel = "external nofollow" >下载</ a > |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
<%@ 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 > |
最后查资料发现在HTML5中提供了download属性,只要写了这个属性可以直接下载图片而不是直接打开;可惜只支持h5,不然省事多了
1
|
< a target = "_blank" download = "aa" href = "img/XD201607000023.gif" rel = "external nofollow" rel = "external nofollow" download = "aa" >下载</ a > |
download中为下载文件的文件名。
以上这篇javaweb页面附件、图片下载及打开(实现方法)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。