• 下载文件


    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>
  • 相关阅读:
    2017ecjtu-summer training # 9 HDU 4544
    2017ecjtu-summer training #6 Gym 100952D
    HDU 1241 DFS
    集训队选拔赛 day4
    Educational Codeforces Round 67 (Rated for Div. 2)
    Codeforces Round #566 (Div. 2)
    Codeforces Round #567 (Div. 2)
    Codeforces Round #568 (Div. 2)
    Codeforces Round #569 (Div. 2)
    牛客练习赛48
  • 原文地址:https://www.cnblogs.com/qfdy123/p/11247500.html
Copyright © 2020-2023  润新知