需求:实现一个具有文件下载功能的网页,主要下载压缩包和图片
两种实现方法:
一:通过超链接实现下载
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>Insert title here</title>
- </head>
- <body>
- <h1>通过链接下载文件</h1>
- <a href="/day06/download/cors.zip">压缩包</a>
- <a href="/day06/download/1.png">图片</a>
- </body>
- </html>
其中day06/download是文档路径,本实例的程序结构如下:
二:通过Servlet程序实现下载
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>Insert title here</title>
- </head>
- <body>
- <h1>通过链接下载文件</h1>
- <a href="/day06/download/cors.zip">压缩包</a>
- <a href="/day06/download/1.png">图片</a>
- <h1>通过servlet程序下载文件</h1>
- <a href="/day06/ServletDownload?filename=cors.zip">压缩包</a>
- <a href="/day06/ServletDownload?filename=1.png">图片</a>
- </body>
- </html>
其中,/day06/ServletDownload 是servlet程序的映射路径
- package com.lsgjzhuwei.servlet.response;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import javax.servlet.ServletException;
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- /**
- * Servlet implementation class ServletDownload
- */
- @WebServlet(asyncSupported = true, urlPatterns = { "/ServletDownload" })
- public class ServletDownload extends HttpServlet {
- private static final long serialVersionUID = 1L;
- /**
- * @see HttpServlet#HttpServlet()
- */
- public ServletDownload() {
- super();
- // TODO Auto-generated constructor stub
- }
- /**
- * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- // TODO Auto-generated method stub
- //获得请求文件名
- String filename = request.getParameter("filename");
- System.out.println(filename);
- //设置文件MIME类型
- response.setContentType(getServletContext().getMimeType(filename));
- //设置Content-Disposition
- response.setHeader("Content-Disposition", "attachment;filename="+filename);
- //读取目标文件,通过response将目标文件写到客户端
- //获取目标文件的绝对路径
- String fullFileName = getServletContext().getRealPath("/download/" + filename);
- //System.out.println(fullFileName);
- //读取文件
- InputStream in = new FileInputStream(fullFileName);
- OutputStream out = response.getOutputStream();
- //写文件
- int b;
- while((b=in.read())!= -1)
- {
- out.write(b);
- }
- in.close();
- out.close();
- }
- /**
- * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- // TODO Auto-generated method stub
- }
- }
重启tomcat服务器,即可实现对压缩包和对图片的下载。
-------------------------------------------------------------------------以上内容转自http://blog.csdn.net/longshengguoji/article/details/39433307--------------------------------------------------------
此外,还有一种下载情况-------------下载其他服务器上的文件
此时,需要使用http将其他服务器文件保存至本地,然后如果有下载需求再另行下载操作。
如下代码实现从其他服务器保存代码至本地:
public class FileUtilz {
public boolean saveUrlAs(String photoUrl, String fileName) {
// 此方法只能用户HTTP协议
System.out.println("photoUrl = " + photoUrl);
System.out.println("fileName = " + fileName);
try {
URL url = new URL(photoUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
DataInputStream in = new DataInputStream(connection.getInputStream());
DataOutputStream out = new DataOutputStream(new FileOutputStream(fileName));
byte[] buffer = new byte[4096];
int count = 0;
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
}
out.close();
in.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public String getDocumentAt(String urlString) {
// 此方法兼容HTTP和FTP协议
StringBuffer document = new StringBuffer();
try {
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
document.append(line + "\n");
}
reader.close();
} catch (MalformedURLException e) {
System.out.println("Unable to connect to URL: " + urlString);
} catch (IOException e) {
System.out.println("IOException when connecting to URL: " + urlString);
}
return document.toString();
}
public static void main(String[] args) {
FileUtilz t = new FileUtilz();
String photoUrl = "http://61.178.11.86:9330/agengr/test.jpg";
String fileName = photoUrl.substring(photoUrl.lastIndexOf("/"));
String filePath = "D:/aaaaa";
boolean flag = t.saveUrlAs(photoUrl, filePath + fileName);
System.out.print("下载状态:" + flag);
}
}
如需下载,代码类似如下:
public String downloadInvoice(){
OutputStream outp = null;
FileInputStream in = null;
try {
Assert.notNull(downloadUrl);
FileUtilz t = new FileUtilz();
String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/") + 1, downloadUrl.length());
String filePath = "D:/aaaaa/" + fileName;
boolean flag = t.saveUrlAs(downloadUrl, filePath);
if(flag){
fileName = URLEncoder.encode(fileName, "UTF-8");
getReponse().addHeader("Content-Disposition", "attachment;filename=" + fileName);
outp = getReponse().getOutputStream();
in = new FileInputStream(filePath);
byte[] b = new byte[1024];
int i = 0;
while ((i = in.read(b)) > 0) {
outp.write(b, 0, i);
}
outp.flush();
}else {
logger.error("下载失败。。。");
}
} catch (Exception e) {
logger.error("下载发票出错", e);
} finally {
try {
if (in != null) {
in.close();
in = null;
}
} catch (Exception e) {
logger.error("下载发票,关闭输入输出流出错", e);
}
}
return null;
}