文件上传与下载Demo

来源:互联网 发布:巨人网络股票代码 编辑:程序博客网 时间:2024/05/23 01:29

上传、下载、列表展示,删除操作servlet

public class FileServlst extends HttpServlet{    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {        String method = req.getParameter("method");        if("upload".equals(method)){            upload(req, resp);        }else if("download".equals(method)){            download(req, resp);        }else if("delete".equals(method)){            delete(req, resp);        }        else{            getFilesList(req, resp);        }    }    // 文件上传    private void upload(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{        // 设置文件编码,防止中文文件名出现乱码(表单提交的中文文件名存在在post提交数据中,所以可以用这个来设置编码)        req.setCharacterEncoding("utf-8");        // 1、创建文件上传工厂类        FileItemFactory fac = new DiskFileItemFactory();        // 2、创建文件上传核心类对象        ServletFileUpload upload = new ServletFileUpload(fac);        if(upload.isMultipartContent(req)){            try{                // 3、把请求数据转换为FileItem对象的集合                List<FileItem> list = upload.parseRequest(req);                for(FileItem item:list){                    if(!item.isFormField()){                        //  获取上传的文件名                        String fileName = item.getName();                        String path = this.getServletContext().getRealPath("/upload");                        File  file = new File(path, fileName);                        // 将上传的文件写入新建的文件中                        item.write(file);                    }                }            }catch(Exception e){                e.printStackTrace();                System.out.println("上传异常");            }        }        getFilesList(req, resp);    }    // 文件列表    private void getFilesList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{        String path = this.getServletContext().getRealPath("/upload");        File file = new File(path);        String[] list = file.list();        req.setAttribute("fileList", list);        req.getRequestDispatcher("/fileList.jsp").forward(req, resp);    }    // 文件下载    private void download(HttpServletRequest req, HttpServletResponse resp) throws IOException{        // 获取用户下载的文件        String fileName = req.getParameter("fileName");        System.out.println(fileName);        fileName = new String(fileName.getBytes("iso-8859-1"),"utf-8");        System.out.println(fileName);        // 如果是中文会存在乱码,因为url的默认编码时iso-8859-1        String path = this.getServletContext().getRealPath("/upload");        File file = new File(path, fileName);        FileInputStream in = new FileInputStream(file);        // 文件名如果有中文,设置响应头编码        fileName = new String(fileName.getBytes("utf-8"),"iso-8859-1");        // 设置下载的响应头        resp.setHeader("content-disposition", "attachment;fileName=" + fileName);        // 获取response字节流        OutputStream out = resp.getOutputStream();        byte[] b = new byte[1024];        int len = -1;        while((len=in.read(b))!=-1){            out.write(b, 0, len);        }        out.close();        in.close();    }    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{        // 获取文件名        String fileName = req.getParameter("fileName");        // 文件名中有中文,设置编码        fileName = new String(fileName.getBytes("iso-8859-1"),"utf-8");        // 获取文件目录        String path = this.getServletContext().getRealPath("/upload");        File file = new File(path, fileName);        file.delete();        getFilesList(req, resp);    }    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {        doGet(req, resp);    }}

列表展示页面list.jsp
注意:因为使用了jstl标签,所以文件头部要加上引用路径

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
   <table align="center" border="1">        <tr>            <th>编号</th>            <th>文件名</th>            <th>操作</th>        </tr>        <c:forEach var="en" items="${requestScope.fileList }" varStatus="vs">            <tr>                <td>${vs.count}</td>                <td>${en}</td>                <td>                    <a href="${pageContext.request.contextPath }/fileServlet?method=delete&fileName=${en}">删除</a>                    <a href="${pageContext.request.contextPath }/fileServlet?method=download&fileName=${en}">下载</a>                </td>            </tr>        </c:forEach>        <tr><td colspan="3" align="center"><a href="${pageContext.request.contextPath }/upload.jsp">上传</a></td></tr>    </table>

文件上传页面

<!-- 当使用form提交表单数据类型为multipart/form-data时,后台不能使用req.getParamater方法获取提交的post数据,只能获取get提交数据 -->    <form action="${pageContext.request.contextPath }/fileServlet?method=upload" enctype="multipart/form-data" method="post">        <input type="file" name="file1"/>        <input type="submit"/>    </form>
原创粉丝点击