文件下載

首先Servlet

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DownServlet
 */
@WebServlet("/DownServlet")
public class DownServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request,response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String path=request.getParameter("path");
        path=new String(path.getBytes("GBK"),"GBK");
        File file=new File(path);
        InputStream in=new FileInputStream(file);
        OutputStream os=response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename="+new String(file.getName()));
        response.addHeader("Content-Length",file.length()+"");
        response.setCharacterEncoding("GBK");
        response.setContentType("application/octet-stream");
        int  data=0;
        while((data=in.read())!=-1){
            os.write(data);     
        }
        os.close();
        in.close();
    }

}

index.jsp

<%@ page language="java" contentType="text/html; charset=GBK"
    pageEncoding="GBK"%>
<!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=GBK">
<title>Insert title here</title>
</head>
<body>
   <a href="DownServlet?path=<%=getServletContext().getRealPath("123.mp3") %>">下載</a>
</body>
</html>

然後我們看看佈局,就是你的目錄下必須有一個mp3文件

運行結果

然後結束啦

發佈了36 篇原創文章 · 獲贊 51 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章