62_2文件上传

文件上传

ps图像上传:通过浏览器客户端将图片上传到服务器的磁盘上

原理

所谓的文件上传就是服务器端通过request对象获取输入流,将浏览器端上传的数据读取出来,保存到服务器端

客户端:

1.请求方式必须是 post

2.需要使用组件< input type="file" name="file">

3.表单必须设置enctype="multipart/form-data"

服务器端:

通过request对象,获取InputStream, 可以将浏览器提交的所有数据读取到

学生管理系统

上传头像

以IO流为基础先输出

jsp 复制代码
    public static void method(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletInputStream in = request.getInputStream();

        StringBuffer sb = new StringBuffer();

        byte[] bs = new byte[1024];
        int len;
        while ((len = in.read(bs)) != -1){
            sb.append(new String(bs,0,len));
        }

        System.out.println(sb.toString());
    }

fileItem是一条一条的,根据不同的数据类型做不同的处理

修改register.jsp
jsp 复制代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

    <h1>注册页面</h1>

    <form action="RegisterServlet" method="post" enctype="multipart/form-data">

        账号:<input type="text" name="username"/><br/>
        密码:<input type="password" name="password"/><br/>
        姓名:<input type="text" name="name"/><br/>
        年龄:<input type="text" name="age"/><br/>
        性别:
        <input type="radio" name="sex" value="man" checked="checked"/>男
        <input type="radio" name="sex" value="woman"/>女
        <br/>
        爱好:
        <input type="checkbox" name="hobbies" value="football"/>足球
        <input type="checkbox" name="hobbies" value="basketball"/>篮球
        <input type="checkbox" name="hobbies" value="shop"/>购物
        <br/>
        上传头像:<input type="file" name="photo"/><br/>
        <input type="submit" value="注册"/>
        <input type="button" value="返回" οnclick="goWelcome()"/>
    </form>

    <script type="text/javascript">
        function goWelcome(){
            window.location = "welcome.html";
        }
    </script>
</body>
</html>
修改RegisterServlet

创建文件上传工厂类的对象

创建文件上传类的对象

解析请求

这里主要是二进制数据的处理,利用发布路径+时间解决文件名重复问题,并且不会改变原文件名

用 File.separator 来代替路径分隔符

java 复制代码
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //创建文件上传工厂类的对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //创建文件上传类的对象
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            //解析请求
            List<FileItem> list = upload.parseRequest(request);

            for (FileItem fileItem : list) {
                if(fileItem.isFormField()){//文本数据

                    String name = fileItem.getFieldName();
                    System.out.println("文本数据 -- " + name);

                }else{//二进制数据

                    //获取项目发布路径 -- D:\\apache-tomcat-8.0.49\\webapps\\MyDay23_upload_war_exploded\\upload
                    String realPath = request.getServletContext().getRealPath("upload");

                    //文件存储目录 -- D:\\apache-tomcat-8.0.49\\webapps\\MyDay23_upload_war_exploded\\upload\\毫秒数
                    String path = realPath + File.separator + System.currentTimeMillis();
                    File file = new File(path);
                    if(!file.exists()){
                        file.mkdirs();
                    }

                    String fileName = fileItem.getName();//获取文件名

                    path = path + File.separator + fileName;//拼接路径

                    InputStream in = fileItem.getInputStream();
                    FileOutputStream out = new FileOutputStream(path);
                    IOUtils.copy(in,out);
                    in.close();
                    out.close();
                }
            }
        } catch (FileUploadException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
实现1
//处理二进制数据 -- 利用传统IO的方式拷贝到本地磁盘
    public static void method01(HttpServletRequest request){
        //创建文件上传工厂类的对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //创建文件上传类的对象
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            //解析请求
            List<FileItem> list = upload.parseRequest(request);

            for (FileItem fileItem : list) {
                if(fileItem.isFormField()){//文本数据

                    String name = fileItem.getFieldName();
                    System.out.println("文本数据 -- " + name);

                }else{//二进制数据

                    InputStream in = fileItem.getInputStream();
                    FileOutputStream out = new FileOutputStream("D:\\test\\xxx.jpg");
                    byte[] bs = new byte[1024];
                    int len;
                    while((len = in.read(bs)) != -1){
                        out.write(bs,0,len);
                    }
                    in.close();
                    out.close();
                }
            }
        } catch (FileUploadException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
实现2
    //处理二进制数据 -- 利用IOUtils实现文件的拷贝
    public static void method02(HttpServletRequest request){
        //创建文件上传工厂类的对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //创建文件上传类的对象
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            //解析请求
            List<FileItem> list = upload.parseRequest(request);

            for (FileItem fileItem : list) {
                if(fileItem.isFormField()){//文本数据

                    String name = fileItem.getFieldName();
                    System.out.println("文本数据 -- " + name);

                }else{//二进制数据

                    InputStream in = fileItem.getInputStream();
                    FileOutputStream out = new FileOutputStream("D:\\test\\xxx.jpg");
                    IOUtils.copy(in,out);
                    in.close();
                    out.close();
                }
            }
        } catch (FileUploadException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
实现3
    //处理二进制数据 -- 获取文件名存储文件
    //问题:文件名重复,会覆盖
    public static void method03(HttpServletRequest request){
        //创建文件上传工厂类的对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //创建文件上传类的对象
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            //解析请求
            List<FileItem> list = upload.parseRequest(request);

            for (FileItem fileItem : list) {
                if(fileItem.isFormField()){//文本数据

                    String name = fileItem.getFieldName();
                    System.out.println("文本数据 -- " + name);

                }else{//二进制数据

                    String path = "D:\\test";//文件存储目录
                    String fileName = fileItem.getName();//获取文件名

                    path = path + File.separator + fileName;//拼接路径

                    InputStream in = fileItem.getInputStream();
                    FileOutputStream out = new FileOutputStream(path);
                    IOUtils.copy(in,out);
                    in.close();
                    out.close();
                }
            }
        } catch (FileUploadException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
实现4
    //处理二进制数据 -- 利用UUID解决文件名重复的问题
    //问题1:改变了原有的文件名
    //问题2:代码的可移植性不高(指定了路径-D:\test)
    public static void method04(HttpServletRequest request){
        //创建文件上传工厂类的对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //创建文件上传类的对象
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            //解析请求
            List<FileItem> list = upload.parseRequest(request);

            for (FileItem fileItem : list) {
                if(fileItem.isFormField()){//文本数据

                    String name = fileItem.getFieldName();
                    System.out.println("文本数据 -- " + name);

                }else{//二进制数据

                    String path = "D:\\test";//文件存储目录

                    //获取随机的UUID对象(理解:随机UUID对象 = 系统参数+对象内存地址+算法)
                    UUID uuid = UUID.randomUUID();

                    String fileName = fileItem.getName();//获取文件名
                    fileName = uuid + fileName;//拼接文件名

                    path = path + File.separator + fileName;//拼接路径

                    InputStream in = fileItem.getInputStream();
                    FileOutputStream out = new FileOutputStream(path);
                    IOUtils.copy(in,out);
                    in.close();
                    out.close();
                }
            }
        } catch (FileUploadException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
实现5
    //处理二进制数据 -- 利用发布路径+时间解决文件名重复问题,并且不会改变原文件名
    public static void method05(HttpServletRequest request){
        //创建文件上传工厂类的对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //创建文件上传类的对象
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            //解析请求
            List<FileItem> list = upload.parseRequest(request);

            for (FileItem fileItem : list) {
                if(fileItem.isFormField()){//文本数据

                    String name = fileItem.getFieldName();
                    System.out.println("文本数据 -- " + name);

                }else{//二进制数据

                    //获取项目发布路径 -- D:\\apache-tomcat-8.0.49\\webapps\\Day23_upload_war_exploded\\upload
                    String realPath = request.getServletContext().getRealPath("upload");

                    //文件存储目录 -- D:\\apache-tomcat-8.0.49\\webapps\\Day23_upload_war_exploded\\upload\\毫秒数
                    String path = realPath + File.separator + System.currentTimeMillis();
                    File file = new File(path);
                    if(!file.exists()){
                        file.mkdirs();
                    }

                    String fileName = fileItem.getName();//获取文件名

                    path = path + File.separator + fileName;//拼接路径

                    InputStream in = fileItem.getInputStream();
                    FileOutputStream out = new FileOutputStream(path);
                    IOUtils.copy(in,out);
                    in.close();
                    out.close();
                }
            }
        } catch (FileUploadException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
相关推荐
LIT-涛16 小时前
JavaEE初学07
数据库·oracle·java-ee
&梧桐树夏16 小时前
JavaEE 线程安全
java-ee·多线程
界面开发小八哥16 小时前
「Java EE开发指南」如何使用Visual JSF编辑器设计JSP?(一)
java·ide·java-ee·编辑器·myeclipse
先睡16 小时前
javaEE
java·java-ee
冷心笑看丽美人16 小时前
Spring 框架七大模块(Java EE 学习笔记03)
学习·spring·架构·java-ee
郑祎亦17 小时前
JavaWeb开发:HTML 页面与接口对接
前端·后端·java-ee·html
Theodore_10221 天前
7 设计模式原则之合成复用原则
java·开发语言·jvm·设计模式·java-ee·合成复用原则
customer082 天前
【开源免费】基于SpringBoot+Vue.JS网上订餐系统(JAVA毕业设计)
java·jvm·vue.js·spring boot·spring cloud·java-ee·开源
Theodore_10222 天前
6 设计模式原则之单一职责原则
java·算法·设计模式·面试·java-ee·javaee·单一职责原则
month1772 天前
Javaee文件的io操作
java·java-ee