zoukankan      html  css  js  c++  java
  • Java中的文件上传2(Commons FileUpload:commons-fileupload.jar)

    相比上一篇使用Servlet原始去实现的文件上传(http://www.cnblogs.com/EasonJim/p/6554669.html),使用组件去实现相对来说功能更多,省去了很多需要配置和处理的地方。

    常用的上传组件有如下几种:  

    Apache 的 Commons FileUpload

    JavaZoom 的 UploadBean

    jspSmartUpload

    但用的最多的应该是Apache 的 Commons FileUpload。

    以下为具体的步骤:

    1、下载组件

    Apache 的 Commons FileUpload包含commons-fileupload.jar和commons-io.jar,下载地址如下:

    commons-fileupload.jar:http://commons.apache.org/proper/commons-fileupload/download_fileupload.cgi

    commons-io.jar:http://commons.apache.org/proper/commons-io/download_io.cgi

    2、新建项目,代码如下:

    参考:http://www.runoob.com/servlet/servlet-file-uploading.html

    JSP:

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
        <head>
            <title></title>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        </head>
        <body>
            <div>
                <form action="UploadServlet" method="POST" enctype="multipart/form-data">
                    <table>
                        <tr>
                            <td><label for="file1">文件1:</label></td>
                            <td><input type="file" id="file1" name="file1"></td>
                        </tr>
                        <tr>
                            <td><label for="file2">文件2:</label></td>
                            <td><input type="file" id="file2" name="file2"></td>
                        </tr>
                        <tr>
                            <td><label for="file3">文件3:</label></td>
                            <td><input type="file" id="file3" name="file3"></td>
                        </tr>
                        <tr>
                            <td><label for="file3">Text:</label></td>
                            <td><input type="text" id="text1" name="text1"></td>
                        </tr>
                        <tr>
                            <td colspan="2"><input type="submit" value="上传" name="upload"></td>
                        </tr>
                    </table>
                </form>
            </div>
        </body>
    </html>

    Servlet:

    注意:全部采用3.0的标注功能。

    package uploadtest;
    
    import java.io.IOException;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.PrintWriter;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.List;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    
    
    
    /**
     * Servlet implementation class UploadServlet
     */
    @WebServlet("/UploadServlet")
    public class UploadServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
           
        /**
         * @see HttpServlet#HttpServlet()
         */
        public UploadServlet() {
            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
        }
    
        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
    
            // 检测是否为多媒体上传
            if (!ServletFileUpload.isMultipartContent(request)) {
                // 如果不是则停止
                PrintWriter writer = response.getWriter();
                writer.println("Error: 表单必须包含 enctype=multipart/form-data");
                writer.flush();
                return;
            }
     
            // 配置上传参数
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
            factory.setSizeThreshold(1024 * 1024 * 3);// 3MB
            // 设置临时存储目录
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));//系统默认的临时文件路径,C:UsersJimAppDataLocalTemp 
            //构造对象
            ServletFileUpload upload = new ServletFileUpload(factory);
             
            // 设置最大文件上传值
            upload.setFileSizeMax(1024 * 1024 * 40);// 40MB
             
            // 设置最大请求值 (包含文件和表单数据)
            upload.setSizeMax(1024 * 1024 * 50);// 50MB
     
            // 构造临时路径来存储上传的文件
            // 这个路径相对当前应用的目录
            String uploadPath = request.getServletContext().getRealPath("/") + "Uploads"+ File.separator+new SimpleDateFormat("yyyyMMdd").format(new Date());
           
             
            // 如果目录不存在则创建
            Tools.isExistDir(uploadPath);//看目录是否已经创建   
     
            try {
                // 解析请求的内容提取文件数据
                List<FileItem> formItems = upload.parseRequest(request);
     
                if (formItems != null && formItems.size() > 0) {
                    // 迭代表单数据
                    for (FileItem item : formItems) {
                        // 处理不在表单中的字段
                        if (!item.isFormField() && item.getName()!=null && !item.getName().equals("")) {
                            String fileName = new SimpleDateFormat("yyyyMMddHHmmsssss").format(new Date())+java.util.UUID.randomUUID() + new File(item.getName()).getName();//由于获取item的名称时是本地的全路径,必须使用file对象进行最后的转换得到最后的文件名
                            String filePath = uploadPath + File.separator + fileName;
                            File storeFile = new File(filePath);
                            // 在控制台输出文件的上传路径
                            System.out.println(filePath);
                            // 保存文件到硬盘
                            item.write(storeFile);
                            System.out.println("上传成功!");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }        
        }
    }

    可以看出,使用组件的方式更为简便,且很多方法已经封装好,直接调用即可。

    测试工程:https://github.com/easonjim/5_java_example/tree/master/uploadtest/test3

    另外,以下还收集了一些组件的深入使用方式:

    http://www.cnblogs.com/h--d/p/5761649.html

    http://blog.csdn.net/qq_32079585/article/details/51344719

    http://www.cnblogs.com/xdp-gacl/p/4200090.html

    http://www.cnblogs.com/hongten/archive/2011/07/26/2117340.html

  • 相关阅读:
    发送电子邮件
    PHP Session
    Cookie
    Python基础语法
    Python中文编码
    Python简介
    PHP文件上传
    基于1.22.1版本的k8s部署
    k8s基于NFS创建动态存储StorageClass
    关于在k8s-v1.20以上版本使用nfs作为storageclass出现selfLink was empty, can‘t make reference
  • 原文地址:https://www.cnblogs.com/EasonJim/p/6576573.html
Copyright © 2011-2022 走看看