0
点赞
收藏
分享

微信扫一扫

《知识点扫盲 · Redis 分布式锁》

墨香子儿 2024-08-15 阅读 27

文件上传

原理

客户端:

服务器端:

学生管理系统

上传头像

以IO流为基础先输出

    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是一条一条的,根据不同的数据类型做不同的处理
上传图片01

修改register.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
@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);
        }
    }

上传图片1

实现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);
        }
    }

加uuid去重

实现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);
        }
    }

会在项目生成两个文件夹

举报

相关推荐

0 条评论