JavaWeb应用(1)文件上传

1.准备工作

文件上传,浏览器上传文件是以流的形式传到服务器端。

1.创建web项目
2.导包

我们需要导入commen-io commen-fileupload

3.文件上传注意事项
  1. 为了保证服务器安全,我们需要将上传的文件放在外界无法访问的目录下,比如WEB-INF目录下
  2. 问了避免因为重名而造成文件覆盖,需要在上传的时候为文件设置唯一的文件名
  3. 要设置文件上传的限制
  4. 可以限制上传文件的类型,在收到上传文件名时,判断后缀是否合法。
4.需要用到的类的介绍

ServletFileUpload负责处理上传的文件数据,并将表单中每个输入项封装为一个FileItem对象,在使用ServletFileUpload请求的时候需要一个DiskFileItemFactory对象,所以我们在进行解析工作前构造好DiskFileItemFactory对象,通过ServletFileUplod对象的构造方法或者setFileItemFactory()方法设置ServletFileUpload对象的fileItemFactory属性。

2.分析文件上传

1.jsp

表单:file类型

enctype="multipart/form-data"这个属性必须添加

表示表单数据是多部分构成,既有文本数据,又有二进制数据。

默认的enctypeapplication/x-www-form-urlencoded只能传输文本数据,不能传输文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <%--文件上传只能是post 方式  get方式有限制为4kb post没有限制--%>
  <%--enctype="multipart/form-data必须要的--%>
  <form action="/file.do" METHOD="post" enctype="multipart/form-data">

    <p>上传者:<input type="text" name="username"> <br></p>
    <p><input type="file" name="file1"><br></p>
    <p><input type="file" name="file2"><br></p>
    <p><input type="submit"> <input type="reset"></p>
    
  </form>
  </body>
</html>
2.servlet
1.设置上传的路径
 //创建文件上传的保存路径 建议在web-inf中创建 因为安全,用户无法访问web-inf下的文件
        String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
        File uploadFile = new File(uploadPath);
        if (!uploadFile.exists()) {
            uploadFile.mkdir();//如果这个文件夹不存在就创建这个文件夹
        }
        //临时路径 假如文件超过预期的大小我们将其放入临时文件夹,过几天自动删除或者提醒用户将其转为永久文件
        String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp");
        File tempFile = new File(tempPath);
        if (!tempFile.exists()) {
            tempFile.mkdir();//如果临时文件夹不存在我们就将其创建
        }
2.创建DiskFileItemFactory对象
1.创建DiskFileItemFactory对象
//1.创建diskFileItemFactory对象处理文件上传路径或者大小限制
        DiskFileItemFactory factory = new DiskFileItemFactory();
2.设置一些值(可有可无)
 
        //给这个工厂设置一个缓冲区,当文件的大小大于这个缓冲区,就将文件传入临时的文件中
        factory.setSizeThreshold(1024 * 1024);//设置缓冲区的大小为1M
        factory.setRepository(tempFile);//临时目录的保存目录需要一个File
3.获得servletFileUpload对象
1.获得servletFileUpload对象
   //2.获取servletFileUpload
        ServletFileUpload upload = new ServletFileUpload(factory);
2.设置一些值(可有可无)


        //监听文件的上传进度
        upload.setProgressListener(new ProgressListener() {
            @Override
            //pBytesRead 已经读取文件的大小
            //pContentLength 文件的总大小
            public void update(long pBytesRead, long pContentLength, int pItems) {
                //这里可以将其设置为%多少
                System.out.println("文件总大小:" + pContentLength + "已上传:" + pBytesRead);
            }
        });
        //处理乱码问题
        upload.setHeaderEncoding("utf-8");
        //设置单个文件的最大值
        upload.setFileSizeMax(1024 * 1024 * 10);
        //设置总共能够上传文件的大小
        upload.setSizeMax(1024 * 1024 * 10);
4.文件上传的处理

1.解析前端请求,进行判断,是否为一个文件

2.处理文件

3.存放的地址

4.文件传输

将这些抽取为一个文件上传的方法:

public static boolean  upload(ServletFileUpload upload,HttpServletRequest request,String uploadPath) throws Exception{
        //设置标志位为false
        boolean flag=false;

        //解析前段请求
        List<FileItem> fileItems = null;
        try {//解析前端请求,封装成FileItem对象,需要从ServletFileUplad对象中获取
            fileItems = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        //fileItem 每一个表单的对象
        for (FileItem fileItem : fileItems) {
            //判断上传的表单是普通的表单,还是带文件的表单
            if(fileItem.isFormField()){
                //getFieldName获得前端表单的那么值
                String name = fileItem.getFieldName();
                String value = fileItem.getString("utf-8");//处理乱码问题
                System.out.println(name+":"+value);
            }else{
                //如果不是普通的表单,就是一个文件
                //==================处理文件================
                //获得表单传来的的名字
                String uploadName = fileItem.getName();
                //处理文件名不合法的问题
                if(uploadName.trim().equals("")||uploadName==null){
                    continue;//完毕
                }
                //获得文件的名字
                String filename = uploadName.substring(uploadName.lastIndexOf("/") + 1);
                //获得文件的后缀名
                String fileExtname = uploadName.substring(uploadName.lastIndexOf(".") + 1);

                /*
                    这里可以处理如果文件的后缀名不是我们想要的就可以直接return
                 */

                //==================存放的地址==============
                //存在哪uuid
                String uuidPath = UUID.randomUUID().toString();
                //文件真实的存储路径
                String realPath=uploadPath+"/"+uuidPath;
                //给每个文件创建一个对应的文件夹
                File realPathFile = new File(realPath);
                if(!realPathFile.exists()){
                    realPathFile.mkdir();
                }

                //==================文件传输================
                //获得文件上传的流
                InputStream inputStream = fileItem.getInputStream();
                //创建一个文件输出流
                //realPath=真实的文件夹
                //真实文件夹下存储一个文件名
                FileOutputStream fileOutputStream = new FileOutputStream(realPath + "/" + filename);
                //创建缓冲区
                byte[] buffer = new byte[1024];
                //判断是否读取完毕
                int len=0;
                //如果大于0 说明还没有读取完毕
                while ((len=inputStream.read(buffer))>0){
                    fileOutputStream.write(buffer);
                }
                //关闭流
                fileOutputStream.close();
                inputStream.close();
                //上传成功设置标志位true
                flag=true;
                //上传成功清除临时文件
                fileItem.delete();

            }
        }
        //将标志位返回
        return flag;
    }

3.文件上传完整的代码

1.servlet
package com.mahui.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

public class FileServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //定义返回的信息为null
        String msg=null;
//上传路径的创建
        //创建文件上传的保存路径 建议在web-inf中创建 因为安全,用户无法访问web-inf下的文件
        String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
        File uploadFile = new File(uploadPath);
        if (!uploadFile.exists()) {
            uploadFile.mkdir();//如果这个文件夹不存在就创建这个文件夹
        }
        //临时路径 假如文件超过预期的大小我们将其放入临时文件夹,过几天自动删除或者提醒用户将其转为永久文件
        String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp");
        File tempFile = new File(tempPath);
        if (!tempFile.exists()) {
            tempFile.mkdir();//如果临时文件夹不存在我们就将其创建
        }
        /*
            1.上传文件,我们一般使用流来获得,我们可以使用request.getInputStream()
            原生态的文件上传流来获取,但是十分的麻烦
            2.我们可以使用Apache的文件上传组件来实现,common-fileupload 它需要依赖于commen-io组件

            ServletFileUpload负责处理文件上传的数据,并将其输入项封装成一个fileItem对象
            在使用ServletFileUpload对象解析时需要一个DiskFileItemFactory对象
            所以我们需要在解析工作前构造好DiskFileItemFactory对象
            通过ServletFileUpload对象的构造方法或setFileItemFactory()方法设置
            ServletFileUpload对象的fileItemFactory属性
         */
    //1.创建diskFileItemFactory对象处理文件上传路径或者大小限制
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //给这个工厂设置一个缓冲区,当文件的大小大于这个缓冲区,就将文件传入临时的文件中
        factory.setSizeThreshold(1024 * 1024);//设置缓冲区的大小为1M
        factory.setRepository(tempFile);//临时目录的保存目录需要一个File

      //2.获取servletFileUpload
        ServletFileUpload upload = new ServletFileUpload(factory);

        //监听文件的上传进度
        upload.setProgressListener(new ProgressListener() {
            @Override
            //pBytesRead 已经读取文件的大小
            //pContentLength 文件的总大小
            public void update(long pBytesRead, long pContentLength, int pItems) {
                //这里可以将其设置为%多少
                System.out.println("文件总大小:" + pContentLength + "已上传:" + pBytesRead);
            }
        });
        //处理乱码问题
        upload.setHeaderEncoding("utf-8");
        //设置单个文件的最大值
        upload.setFileSizeMax(1024 * 1024 * 10);
        //设置总共能够上传文件的大小
        upload.setSizeMax(1024 * 1024 * 10);
//3.处理上传文件
        //定义标志位false 先是上传失败
        boolean flag=false;
        try {
            //给标志位重新复制
             flag = upload(upload, req, uploadPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        PrintWriter out = resp.getWriter();
        resp.setCharacterEncoding("utf-8");
        //如果标志位为true
        if(flag){
            //上传成功
            out.write("上传成功");
        }else {
            //否则上传失败
            out.write("上传失败");
        }


    }

    //进行上传 文件的方法

    public static boolean  upload(ServletFileUpload upload,HttpServletRequest request,String uploadPath) throws Exception{
        //设置标志位为false
        boolean flag=false;

        //解析前段请求
        List<FileItem> fileItems = null;
        try {//解析前端请求,封装成FileItem对象,需要从ServletFileUplad对象中获取
            fileItems = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        //fileItem 每一个表单的对象
        for (FileItem fileItem : fileItems) {
            //判断上传的表单是普通的表单,还是带文件的表单
            if(fileItem.isFormField()){
                //getFieldName获得前端表单的那么值
                String name = fileItem.getFieldName();
                String value = fileItem.getString("utf-8");//处理乱码问题
                System.out.println(name+":"+value);
            }else{
                //如果不是普通的表单,就是一个文件
                //==================处理文件================
                //获得表单传来的的名字
                String uploadName = fileItem.getName();
                //处理文件名不合法的问题
                if(uploadName.trim().equals("")||uploadName==null){
                    continue;//完毕
                }
                //获得文件的名字
                String filename = uploadName.substring(uploadName.lastIndexOf("/") + 1);
                //获得文件的后缀名
                String fileExtname = uploadName.substring(uploadName.lastIndexOf(".") + 1);

                /*
                    这里可以处理如果文件的后缀名不是我们想要的就可以直接return
                 */

                //==================存放的地址==============
                //存在哪uuid
                String uuidPath = UUID.randomUUID().toString();
                //文件真实的存储路径
                String realPath=uploadPath+"/"+uuidPath;
                //给每个文件创建一个对应的文件夹
                File realPathFile = new File(realPath);
                if(!realPathFile.exists()){
                    realPathFile.mkdir();
                }

                //==================文件传输================
                //获得文件上传的流
                InputStream inputStream = fileItem.getInputStream();
                //创建一个文件输出流
                //realPath=真实的文件夹
                //真实文件夹下存储一个文件名
                FileOutputStream fileOutputStream = new FileOutputStream(realPath + "/" + filename);
                //创建缓冲区
                byte[] buffer = new byte[1024];
                //判断是否读取完毕
                int len=0;
                //如果大于0 说明还没有读取完毕
                while ((len=inputStream.read(buffer))>0){
                    fileOutputStream.write(buffer);
                }
                //关闭流
                fileOutputStream.close();
                inputStream.close();
                //上传成功设置标志位true
                flag=true;
                //上传成功清除临时文件
                fileItem.delete();

            }
        }
        //将标志位返回
        return flag;
    }

}
2.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <%--文件上传只能是post 方式  get方式有限制为4kb post没有限制--%>
  <%--enctype="multipart/form-data必须要的--%>
  <form action="/file.do" METHOD="post" enctype="multipart/form-data">

    <p>上传者:<input type="text" name="username"> <br></p>
    <p><input type="file" name="file1"><br></p>
    <p><input type="file" name="file2"><br></p>
    <p><input type="submit"> <input type="reset"></p>
    
  </form>
  </body>
</html>

4.学习到了什么?

1.UUID
  private static final long serialVersionUID = -4856846361193249489L;

serialVersionUID主要是为了保证原子性的。

在网络传输中的东西都需要序列化。

我们通常写的实体类pojo,如果想要在多个电脑上运行,即需要传输。我们需要将对象都序列化了。pojo类需要实现

java.io.Serializable接口

进入Serializable接口,发现其是一个空接口。

将有一个方法的接口叫做:函数式接口

没有方法的接口叫做:标记接口

所以Serializable是一个标记接口

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值