package com.zy.down; import java.io.FileInputStream; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class FileDown */ @WebServlet("/FileDown") public class FileDown extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String file = request.getParameter("file"); //客户端传递的需要下载的文件名 String path = request.getServletContext().getRealPath("/img")+"/"+file; //默认认为文件在当前项目的根目录 FileInputStream fis = new FileInputStream(path); response.setCharacterEncoding("utf-8"); //attachment 附件--有附件为下载,无附件为预览 response.setHeader("Content-Disposition", "attachment; filename="+file); ServletOutputStream out = response.getOutputStream(); byte[] bt = new byte[1024]; int length = 0; //边读边写 while((length=fis.read(bt))!=-1){ out.write(bt,0,length); } out.close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <a href="FileDown?file=110.jpg">下载图片</a> </body> </html>