JSP文件上传

来源:互联网 发布:二叉树的深度 java 编辑:程序博客网 时间:2024/06/09 16:37

概述:
文件上传是网站中很常用的一个功能,下面是一个文件上传的基本demo。
由于是使用的新版jar包,所以需要依赖以下几个jar包:
catalina.jar
commons-fileupload-1.3.1.jar
commons-io-2.4.jar

public class UpLoadServlet extends HttpServlet {    private static final long serialVersionUID = 1L;    /**     * 该方法用于文件上传     * @jar catalina.jar commons-fileupload-1.3.1.jar commons-io-2.4.jar     */    public void service(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        response.setContentType("text/html");        request.setCharacterEncoding("UTF-8");        /*         * 文件上传逻辑         */        //创建DiskFileItemFactory对象,为解析器提供解析时的一些缺省配置        DiskFileItemFactory dfif = new DiskFileItemFactory();        //创建解析器        ServletFileUpload sfu = new ServletFileUpload(dfif);        //使用解析器解析分析器        try {            //解析request请求            List<FileItem> items = sfu.parseRequest(request);            for(FileItem item : items) {                //如果是普通表单类                if(item.isFormField()) {                    continue;                }                //执行上传文件动作                //根据servlet上下文获得服务器中实际物理路径                //此处可以更改为其他另存为的路径                String path = getServletContext().getRealPath("/upload");                //获取文件名                String fileName = item.getName();                //获取文件后缀                String fileSuffix = fileName.substring(fileName.lastIndexOf("."));                //设置当前系统时间毫秒数的值为文件名(无需考虑同步,几率极其低)                String newName = Calendar.getInstance().getTimeInMillis()+fileSuffix;                //File.separator是获取一个兼容操作系统路径的"/"                File file = new File(path+File.separator+newName);                try {                    //写入文件                    item.write(file);                } catch (Exception e) {                    e.printStackTrace();                }            }        } catch (FileUploadException e) {            e.printStackTrace();        }    }}

jsp页面代码

<!-- enctype="multipart/form-data"表示不对上传的消息进行编码 -->    <form action="upload.do" enctype="multipart/form-data" method="post">    <input type="file" name="fileName">    <input type="submit" value="提交">

这里注意:上传后的文件是上传到TomCat中该的项目的目录中的upload文件夹,如果将TomCat上项目移除,上传的文件也会随之消失。

0 0
原创粉丝点击