• web---资源的下载及中文乱码问题


    1、html网页,超链接交由Servlet处理

    <!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>

    2.web.xml----Servlet的注册

        <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 处名字必须相同

    3.Servlet的实现

    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);
            }
        }
    
    }
  • 相关阅读:
    Xpath提取一个标签里的所有文本
    Mac Sublime Text 3
    激活pycharm
    Mac 终端命令大全
    操作dict时避免出现KeyError的几种方法
    JQ 选择器大全
    调用百度编辑器
    模拟 Ajax 上传
    图片上传
    PHP 字符串去掉空格
  • 原文地址:https://www.cnblogs.com/nlw-blog/p/10772247.html
Copyright © 2020-2023  润新知