Java-response -下载文件的基本代码
1、先建立一个html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1>使用a标签直接指向服务器上的资源</h1> <a href="/WEBTEST1/download/a.flv">a.flv</a> <br> <a href="/WEBTEST1/download/a.jpg">a.jpg</a> <br> <a href="/WEBTEST1/download/a.mp3">a.mp3</a> <br> <a href="/WEBTEST1/download/a.mp4">a.mp4</a> <br> <a href="/WEBTEST1/download/a.txt">a.txt</a> <br> <a href="/WEBTEST1/download/a.zip">a.zip</a> <br> <h1>使用服务器端编码的方式下载文件</h1> <a href="/WEBTEST1/downloadServlet?filename=a.flv">a.flv</a> <br> <a href="/WEBTEST1/downloadServlet?filename=a.jpg">a.jpg</a> <br> <a href="/WEBTEST1/downloadServlet?filename=a.mp3">a.mp3</a> <br> <a href="/WEBTEST1/downloadServlet?filename=a.mp4">a.mp4</a> <br> <a href="/WEBTEST1/downloadServlet?filename=a.txt">a.txt</a> <br> <a href="/WEBTEST1/downloadServlet?filename=a.zip">a.zip</a> <br> </body> </html>
2、response代码
package com.king.servlet; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.coyote.Response; public class downloadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获得需要下载文件的名称 String filename = request.getParameter("filename"); // 告诉客户端要下载的文件类型--客户端通过MIME区分类型 response.setContentType(this.getServletContext().getMimeType(filename)); // 告诉客户端不要直接打开 要下载 response.setHeader("Content-Disposition", "attachment;filename=" + filename); // 获取文件的绝对路径 String realpath = this.getServletContext().getRealPath("download/" + filename); // 获得该文件的输入流 InputStream input = new FileInputStream(realpath); int len = 0; byte[] buffer = new byte[1024]; // 输出流 ServletOutputStream out = response.getOutputStream(); while ((len = input.read(buffer)) > 0) // len的长度等于input.read(buffer)并且大于0的时候一直输出 { out.write(buffer, 0, len); } input.close(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }