标签:-- 输入流 下载 har protect cte -name xtend 处理
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>实现文件的下载功能</h1> <a href="ImgServlet?filename=a.jpg">aa</a><br> <a href="ImgServlet?filename=b.jpg">bb </a><br> <a href="ImgServlet?filename=图片.png">图片</a><br> </body> </body> </html>
<servlet> <servlet-name>DownLoadImgServlet</servlet-name>。--1 <servlet-class>nee.DownLoadImgServlet</servlet-class> --这是我自己的路径 </servlet> <servlet-mapping> <servlet-name>DownLoadImgServlet</servlet-name>--2 <url-pattern>/ImgServlet</url-pattern>--网页的映射,对应html上a的超链接 </servlet-mapping>
--1 2 处名字必须相同
package nee; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URLEncoder; @WebServlet(name = "DownLoadImgServlet") public class DownLoadImgServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* 用字节输出流向文件写资源 资源需要从输入流中读入 输入流为图片构成的输入流 */ String filename=request.getParameter("filename"); //解决中文找不到资源路径的问题 filename = new String(filename.getBytes("ISO-8859-1"),"UTF-8"); //将文件转化为输入流 InputStream is=getServletContext().getResourceAsStream("download/"+filename); //解决文件名不显示中文的问题 filename=URLEncoder.encode(filename,"UTF-8"); //声明这是一个下载的文件 response.setHeader("Content-Disposition","attachment;filename="+filename); OutputStream os=response.getOutputStream(); int len=0; byte[] buffer = new byte[1024]; while ((len=is.read(buffer) )!= -1){ os.write(buffer,0,len); } } }
标签:-- 输入流 下载 har protect cte -name xtend 处理
原文地址:https://www.cnblogs.com/nlw-blog/p/10772247.html