• eclipse之java中文件的上传操作


    一、单文件上传:
        1.首先前端页面的编写只有一个注意项:就是上传的文件中有图片时更改表单项的entype属性为:enctype="multipart/form-data"

          简单说明一下:表单中enctype="multipart/form-data"的意思,是设置表单的MIME编码。默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件    上传;  只有使用了multipart/form-data,才能完整的传递文件数据,进行下面的操作.
          想知道具体为什么的可以百度一下

          下面是笔者写的前端jsp页面(特别简陋):

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!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=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
        <form action="${pageContext.request.contextPath}/BServlet" method="post"  enctype="multipart/form-data">
            昵称:<input type="text" name="Name"><br />
            <input type="file" name="File"> <br />
            <input type="submit" value="上传">
        </form>
    </body>
    </html>

        2.servlet的编写:

          2.1首先是导包:

            > 我们一般情况下使用commons-fileupload-1.3.1.jar这个工具来解析多部件请求。
                    > fileupload 依赖 commons-io 所以我们要是Filtupload需要同时导入io包。

                                所以我们需要导入的两个包笔者已经上传到百度云了,需要的朋友可以在这下载(链接:http://pan.baidu.com/s/1c17Ohqw 密码:v3g8)

          2.2接下来编写servlet:

            先来做一些简单的说明:

              DiskFileItemFactory - 工厂类,用于构建一个解析器实例。
                     ServletFileUpload - 解析器类,通过该类实例来解析request中的请求信息。

              FileItem - 工具会将我们请求中每一个部件,都封装为一个FileItem对象,处理文件上传时,只需要调用该对象的方法
                          -    方法:
                              boolean    isFormField()  --> 当前表单项是否是一个普通表单项,true是普通表单项, false是文件表单项
                              String    getContentType() --> 返回的是文件的类型,是MIME值
                              String    getFieldName()   --> 获取表单项的name属性值
                              String    getName()         --> 获取上传的文件的名字
                              long getSize()          --> 获取文件的大小
                              String    getString(String encoding) --> 获取表单项的value属性值,需要接受一个编码作为参数。
                              void    write(File file)    --> 将表单项中的内容写入到磁盘中
                                 (这是我们经常需要用到的一些方法)
                   > 使用步骤:
                        1.获取工厂类实例[DiskFileItemFactory]
                        2.获取解析器类实例[ServletFileUpload]
                        3.解析request获取FileItem[parseRequest()]

          下面是笔者写的一段简短的servlet代码(将上传的文件保存到电脑),希望对大家有写帮助:

      

    protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            // 用于测试前端页面是否与servlet连接好
            System.out.println("连接没问题");
            // 工厂类
            DiskFileItemFactory dfif = new DiskFileItemFactory();
            // 用于文件上传
            ServletFileUpload fileupload = new ServletFileUpload(dfif);
            // 设置文件大小(单个文件大小限制100k)
            fileupload.setFileSizeMax(1034 * 100);
            try {
                // 获取前端上传的文件
                List<FileItem> fileList = fileupload.parseRequest(request);
                for (FileItem item : fileList) {
                    if (item.isFormField()) {
                        // 普通表单项(也就是jsp页面中name="Name"中的内容)
                        String name = item.getFieldName();
                        String value = item.getString("utf-8");
                        System.out.println(name + ":" + value);
                    } else {
                        // 文件表单项
                        long size = item.getSize();
                        //文件的下载位置C:/Users/TYD/Desktop/123.jpg并命名为123.jpg
                        String path = "C:/Users/TYD/Desktop/123.jpg";
                        File f = new File(path);
                        try {
                            item.write(f);
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            } catch (FileUploadException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

      try和catch是抛出异常

         下面这段代码是将上传的文件保存服务器:

        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            System.out.println("连接没问题");
            //工厂类
            DiskFileItemFactory dfif=new DiskFileItemFactory();
            //用于文件上传
            ServletFileUpload fileupload=new ServletFileUpload(dfif);
            //设置文件大小(单个文件大小限制50k)
            fileupload.setFileSizeMax(1034*50);
    
            //设置服务器地址
            ServletContext servletContext = request.getServletContext();
            //在服务器创建一个upload文件
            String realPath = servletContext.getRealPath("/upload");
            System.out.println("realPath"+realPath);
            File file = new File(realPath);
            //判断文件是否为空
            if(!file.exists()){
                //如果文件不存在,创建文件
                file.mkdir();
            }
            try {
                //获取前端上传的文件
                List<FileItem> fileList=fileupload.parseRequest(request);
                for(FileItem item:fileList){
                    if(item.isFormField()){
                        //普通表单项
                        String name=item.getFieldName();
                        String value=item.getString("utf-8");
                        System.out.println(name+":"+value);
                    }else{
                        //文件表单项
                        long size=item.getSize();//获取文件格式
                        //防止上传空文件
                        if(size ==0){
                            continue;
                        }
                        
                        System.out.println("size:"+size);
                        //设置新创建的文件的名字
                        String contentType = item.getContentType();
                        String name = item.getName();
                        if(name.contains("\")){
                            name = name.substring(name.lastIndexOf("\")+1);
                        }
                        System.out.println("name:"+name);
                        //防止同名文件覆盖
                        String prefix = UUID.randomUUID().toString();
                        //去除文件中的-
                        prefix = prefix.replace("-","");
                        String fileName = prefix+"_"+name;
                        String fieldName = item.getFieldName();
                        System.out.println(size+":"+contentType+":--------"+name+":"+fieldName);
                        
                        try {
                            item.write(new File(realPath+"\"+fileName));
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }catch(FileSizeLimitExceededException e){
                System.out.println("文件大小不可以超过50K");
            } catch (FileUploadException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
        }

      接下来便是上传多个文件到服务器

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            System.out.println("连接没问题");
            //工厂类
            DiskFileItemFactory dfif=new DiskFileItemFactory();
            //用于文件上传
            ServletFileUpload fileupload=new ServletFileUpload(dfif);
            //设置多个文件总大小
            fileupload.setSizeMax(1024*200);
            //设置服务器地址
            ServletContext servletContext = request.getServletContext();
            //在服务器创建一个upload文件
            String realPath = servletContext.getRealPath("/upload");
            System.out.println("realPath"+realPath);
            File file = new File(realPath);
            //判断文件是否为空
            if(!file.exists()){
                //如果文件不存在,创建文件
                file.mkdir();
            }
            try {
                //获取前端上传的文件
                List<FileItem> fileList=fileupload.parseRequest(request);
                for(FileItem item:fileList){
                    if(item.isFormField()){
                        //普通表单项
                        String name=item.getFieldName();
                        String value=item.getString("utf-8");
                        System.out.println(name+":"+value);
                    }else{
                        //文件表单项
                        long size=item.getSize();//获取文件格式
                        //防止上传空文件
                        if(size ==0){
                            continue;
                        }
                        
                        System.out.println("size:"+size);
                        //设置新创建的文件的名字
                        String contentType = item.getContentType();
                        String name = item.getName();
                        if(name.contains("\")){
                            name = name.substring(name.lastIndexOf("\")+1);
                        }
                        System.out.println("name:"+name);
                        //防止同名文件覆盖
                        String prefix = UUID.randomUUID().toString();
                        prefix = prefix.replace("-","");
                        String fileName = prefix+"_"+name;
                        String fieldName = item.getFieldName();
                        System.out.println(size+":"+contentType+":--------"+name+":"+fieldName);
                        
                        try {
                            item.write(new File(realPath+"\"+fileName));
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }catch(SizeLimitExceededException e){
                System.out.println("总大小不可以超过150k");
            } catch (FileUploadException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
        }

    好了,关于文件的上传就到这里。希望对大家有些帮助。。。

  • 相关阅读:
    明确方向,勇往直前
    每日一笔记之3:QTconnect()
    每日一笔记之2:QT之坐标系统:
    每日一笔记之1:静态成员函数
    QT对话框模式与非模式
    Objective-C-实例变量与属性的关系
    Objective-C编码规范
    CocoaPods的安装与使用
    design_model(18)observe
    design_model(17)state
  • 原文地址:https://www.cnblogs.com/TYDBLOG/p/7389614.html
Copyright © 2020-2023  润新知