文件下载和上一篇文件上传很像,就不多说了,传一个我写的一个下载歌曲的代码:

下面是Servlet代码:

public class DownLoadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
   
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext servletContext= request.getServletContext();
        String filename="风吹麦浪.mp3";
        String path=servletContext.getRealPath("/WEB-INF/"+filename);
        File file =new File(path);
        String type=servletContext.getMimeType(path);
        InputStream in = new FileInputStream(file);
        response.setContentType(type);
        filename =new String(filename.getBytes("gbk"),"iso8859-1");
        response.setHeader("Content-Disposition", "attachment;filename"+filename);
        PrintWriter out=response.getOutputStream();
        IOUtils.copy(in, out);
     in.close(); } }

下面是jsp代码:

<body>
    <a href="${pageContext.request.contextPath}/DownLoadServlet">下载</a>
</body>

注意要导入一个io的jar包: