文件下载

public HttpServletResponse download(String path, HttpServletResponse response) { try { // path是指欲下载的文件的路径。 File file = new File(path); // 取得文件名。 String filename = file.getName(); // 取得文件的后缀名。 String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase(); // 以流的形式下载文件。 InputStream fis = new BufferedInputStream(new FileInputStream(path)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); // 设置response的Header response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes())); response.addHeader("Content-Length", "" + file.length()); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); toClient.write(buffer); toClient.flush(); toClient.close(); } catch (IOException ex) { ex.printStackTrace(); } return response; } public void downloadLocal(HttpServletResponse response) throws FileNotFoundException { // 下载本地文件 String fileName = "Operator.doc".toString(); // 文件的默认保存名 // 读到流中 InputStream inStream = new FileInputStream("c:/Operator.doc");// 文件的存放路径 // 设置输出的格式 response.reset(); response.setContentType("bin"); response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // 循环取出流中的数据 byte[] b = new byte[100]; int len; try { while ((len = inStream.read(b)) > 0) response.getOutputStream().write(b, 0, len); inStream.close(); } catch (IOException e) { e.printStackTrace(); } } public void downloadNet(HttpServletResponse response) throws MalformedURLException { // 下载网络文件 int bytesum = 0; int byteread = 0; URL url = new URL("windine.blogdriver.com/logo.gif"); try { URLConnection conn = url.openConnection(); InputStream inStream = conn.getInputStream(); FileOutputStream fs = new FileOutputStream("c:/abc.gif"); byte[] buffer = new byte[1204]; int length; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; System.out.println(bytesum); fs.write(buffer, 0, byteread); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }

public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception { File f = new File(filePath); if (!f.exists()) { response.sendError(404, "File not found!"); return; } BufferedInputStream br = new BufferedInputStream(new FileInputStream(f)); byte[] buf = new byte[1024]; int len = 0; response.reset(); // 非常重要 if (isOnLine) { // 在线打开方式 URL u = new URL("file:///" + filePath); response.setContentType(u.openConnection().getContentType()); response.setHeader("Content-Disposition", "inline; filename=" + f.getName()); // 文件名应该编码成UTF-8 } else { // 纯下载方式 response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition", "attachment; filename=" + f.getName()); } OutputStream out = response.getOutputStream(); while ((len = br.read(buf)) > 0) out.write(buf, 0, len); br.close(); out.close(); }
下载一个本地图片:

package com.servlet; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class DownloadServlet extends HttpServlet { /** * Constructor of the object. */ public DownloadServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //String realPath=this.getServletContext().getRealPath("/download/1.gif"); //String realPath="E:\\myeclipes_woekspace\\one\\TestWeb\\download\\1.gif"; //String realPath="E:\\myeclipes_woekspace\\one\\TestWeb\\download\\图片.jpg"; //String realPath="E:\\myeclipes_woekspace\\one\\TestWeb\\download\\text1.txt"; String realPath="C:/Users/Administrator.PMIMP83HWNIKWOV/Workspaces/MyEclipse 9/TestWeb/WebRoot/download/down1.jpg"; File f=new File(realPath);//用来下载的文件 String filename="down1.jpg"; response.reset();//清空response //response.addHeader("Content-Dispotion", "attachment;filename="+filename);注意,设置头文件不要写错了,妈蛋,少些了一个s,一直下载的是DownloadServlet为名字的文件 response.setHeader("Content-Disposition", "attachment;filename=" + filename);//第一步设置头文件,通过头文件,告诉浏览器以下载方式打开数据,是addHeader或setHeader都可以,只要头文件正确就好。注意下面一定要设置ContentType,不然在浏览器只是显示图片 //response.setContentType("application/octet-stream"); //response.setContentType("image/jpeg"); response.setContentType("application/x-download"); FileInputStream in=new FileInputStream(f); //将要下载的文件的内容写入response的out流中 OutputStream out=response.getOutputStream(); int len=0; byte buffer[]=new byte[1024]; while((len=in.read(buffer))>0){ out.write(buffer, 0, len); } in.close(); //在销毁response的时候服务器会自动关闭与response相关流 } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
如果下载的文件时中文名,需要在头文件中的filename哪里设置编码
IE这样:response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename,"UTF-8"));
其他浏览器:将filename解析 filename=new String(filename.getBytes("utf-8"),"iso-8859-1");

String filename="图片.jpg"; response.reset();//清空response //response.addHeader("Content-Dispotion", "attachment;filename="+filename);注意,设置头文件不要写错了,妈蛋,少些了一个s,一直下载的是DownloadServlet为名字的文件 response.setHeader("Content-Disposition", "attachment;filename=" + filename);//第一步设置头文件,通过头文件,告诉浏览器以下载方式打开数据,是addHeader或setHeader都可以,只要头文件正确就好。注意下面一定要设置ContentType,不然在浏览器只是显示图片 //response.setContentType("application/octet-stream"); //response.setContentType("image/jpeg"); response.setContentType("application/x-download"); FileInputStream in=new FileInputStream(f);

package com.servlet; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class DownloadServlet extends HttpServlet { /** * Constructor of the object. */ public DownloadServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); request.setCharacterEncoding("utf-8"); //String realPath=this.getServletContext().getRealPath("/download/1.gif"); //String realPath="E:\\myeclipes_woekspace\\one\\TestWeb\\download\\1.gif"; //String realPath="E:\\myeclipes_woekspace\\one\\TestWeb\\download\\图片.jpg"; //String realPath="E:\\myeclipes_woekspace\\one\\TestWeb\\download\\text1.txt"; String realPath="C:/Users/Administrator.PMIMP83HWNIKWOV/Workspaces/MyEclipse 9/TestWeb/WebRoot/download/图片.jpg"; File f=new File(realPath);//用来下载的文件 String filename="图片.jpg"; //filename=new String(filename.getBytes("iso-8859-1"),"utf-8"); //System.out.println(filename); response.reset();//清空response //response.addHeader("Content-Dispotion", "attachment;filename="+filename);注意,设置头文件不要写错了,妈蛋,少些了一个s,一直下载的是DownloadServlet为名字的文件 response.setHeader("Content-Disposition", "attachment;filename=" +new String(filename.getBytes("utf-8"),"iso-8859-1"));//第一步设置头文件,通过头文件,告诉浏览器以下载方式打开数据,是addHeader或setHeader都可以,只要头文件正确就好。注意下面一定要设置ContentType,不然在浏览器只是显示图片 /* IE使用URLEncoder.encode(filename,"utf-8"))有效 * new String(filename.getBytes("utf-8"),"iso-8859-1"));适用于其他浏览器。 * */ //response.setContentType("application/octet-stream"); //response.setContentType("image/jpeg"); response.setContentType("application/x-download"); FileInputStream in=new FileInputStream(f); //将要下载的文件的内容写入response的out流中 OutputStream out=response.getOutputStream(); int len=0; byte buffer[]=new byte[1024]; while((len=in.read(buffer))>0){ out.write(buffer, 0, len); } in.close(); //在销毁response的时候服务器会自动关闭与response相关流 } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
下载网络文件
URL url = new URL("windine.blogdriver.com/logo.gif"); try { URLConnection conn = url.openConnection(); InputStream inStream = conn.getInputStream();
URL类解析路径,url获取conn,conn获取InputStream
后面使用输入流写入输出流就是了,setHeader那些还是一样的
还有一种下载方式但是有局限性,就是超链接下载
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'textdownload.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <a href="/TestWeb/download/down1.jpg">down1.jpg</a><br/> <a href="/TestWeb/download/dm.zip">dm.zip</a> </body> </html>
这种方式下载有局限性,浏览器能够识别的,浏览器就会直接打开,不能识别的才会有下载选项。这里的jpg会被打开,zip会下载