jsp页面:
pageEncoding="utf-8"%>
Insert title here下载index.jsp
下载1.jpg
下载test.jsp
Servlet:
packageorg.jimmy.testwebproject2019012602.servlet.download;importjava.io.FileInputStream;importjava.io.IOException;importjava.io.InputStream;importjavax.servlet.ServletException;importjavax.servlet.ServletOutputStream;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;/***@authorYang.Yuxin(Jimmy)
* @date 2019年2月14日 下午5:39:47
* @detail 下载Servlet*/
public class DownloadServlet extendsHttpServlet {private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {try{
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String urlStr= request.getParameter("urlStr");
String fileName= urlStr.substring(urlStr.lastIndexOf("/") + 1);
response.setContentType("application/x-msdownload; charset=utf-8");
response.addHeader("Content-Disposition", "attachment; filename=" +fileName);//这个是使用项目的相对路径来获取文件的输入流
InputStream is =request.getServletContext().getResourceAsStream(urlStr);/*//这个可以使用绝对路径来获取文件的输入流
FileInputStream fis = new FileInputStream("D:\\Document\\201902\\20190228\\Test\\1.jpg");*/ServletOutputStream sos=response.getOutputStream();int fileLength =is.available();int cacheLength = 1024;if(fileLength
cacheLength=fileLength;
}int len =cacheLength;byte[] bytes = new byte[cacheLength];while((len = is.read(bytes, 0, len)) != -1) {
sos.write(bytes);
}
sos.flush();
sos.close();
is.close();
}catch(Exception e) {
e.printStackTrace();
}
}protected void doPost(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {
doGet(request, response);
}
}