文件下载

来源:互联网 发布:淘宝引导下单转化率 编辑:程序博客网 时间:2024/06/06 01:14

首先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文件

运行结果

然后结束啦

0 0