简单页面内的文件上传操作

文件上传

1.先导入依赖

涉及两个重要的文件上传的jar包 commons-fileupload commons-io

   <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <!-- Jsp依赖-->
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.3</version>
      <scope>provided</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
      <!-- Servlet依赖-->
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
      <scope>provided</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/taglibs/standard -->
    <dependency>
      <!-- Standard标签库-->
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl-api -->
    <dependency>
      <!-- Jstl表达式依赖-->
      <groupId>javax.servlet.jsp.jstl</groupId>
      <artifactId>jstl-api</artifactId>
      <version>1.2</version>
    </dependency>

    <dependency>
      <!-- Java连接数据库-->
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.47</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.11.0</version>
    </dependency>



2.配置jsp首页的点击上传页面
<body>
<h2>Hello World!</h2>


<%--  get:上传有限制
      post:没有限制    --%>
          <%--  ${pageContext.request.contextPath}获取服务器路径   --%>
<form action="${pageContext.request.contextPath}/upload.do"   enctype="multipart/form-data" method="post">
    上传用户:<input type="text" name="username">
    <p><input type="file" name="file1"></p>

    <p><input type="file" name="file2"></p>

    <p> <input type="submit"> | <input type="reset"></p>
</form>
</body>

设置一个jsp接受响应msg

<body>

${msg}

</body>

3.Servlet

有的if是需要否定的需要加上! 记得检查代码有没有 少一个感叹号就不一样 还有 这个上传是必须使用post 所以走的dopost 不要写在doget上面

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 FileDown extends HttpServlet {


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //判断上传的文件是普通表单还是带文件的表单
        if(!ServletFileUpload.isMultipartContent(req)){
            return;//终止方法运行,说明是一个普通表单
        }

        //创建文件上传的路径,建议在WEB-INF路径下  比较安全  用户无法直接访问上传的文件
        String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
        File uploadFile = new File(uploadPath);
        if(!uploadFile.exists()){
            uploadFile.mkdir();//创建这个目录
        }

        //缓存  临时文件
        //当文件过于大的时候  我们就把他放到一个临时文件中 过几天删除 或提醒用户转化为永久
        String tmpPath = this.getServletContext().getRealPath("/WEB-INF/temp");
        File file = new File(uploadPath);
        if(!file.exists()){
            file.mkdir();//创建这个临时目录
        }

        //处理上传的文件,一般都需要流来获取,我们可以使用request.getInputStream(),原生态的文件上传 十分麻烦
        //但是我们建议用apache的文件上传组件来实现  common-fileupload 它依赖common-io组件

        /*ServletFileUpload负责处理文件上传的数据,并将每个输入的FileItem对象
        在使用ServletFileUpload对象解析请求时需要DiskFileItemFactory对象
        所以我们需要在解析工作时构造好DiskFileItemFactory对象
        通过ServletFileUpLoad对象的构造方法或setFileItemFactory()方法设置ServletFileUpload对象的fileItemFactory属性
        */


        try {


        //1.创建DiskFileItemFactory对象,处理文件上传路径或大小限制的
        DiskFileItemFactory factory =getDiskFileItemFactory(file);

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


        //3.处理上传文件
        String msg = uploadPareRequest(upload, req, uploadPath);

        //servlet请求转发
        req.setAttribute("msg", msg);
        req.getRequestDispatcher("info.jsp").forward(req, resp);
        }catch (FileUploadException e){
            e.printStackTrace();
        }
    }


    public  static  DiskFileItemFactory getDiskFileItemFactory(File file){
        //1.创建DiskFileItemFactory对象,处理文件上传路径或大小限制的
        DiskFileItemFactory factory =new DiskFileItemFactory();
        //通过这个工厂设置一个缓冲区,当上传的文件大于缓冲区时,将他放到临时文件
        factory.setSizeThreshold(1024*1024);  //缓冲区大小为1M
        factory.setRepository(file);//临时目录的保存目录需要一个File
        return factory;
    }
    public  static  ServletFileUpload getServletFileUpload(DiskFileItemFactory factory){




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

        //监听上传速度(自己加的小插件)
        upload.setProgressListener(new ProgressListener() {
            @Override
            //pBytesRead:已经读到的文件大小
            //pContentLength:文件大小
            public void update(long pBytesRead, long pContentLength, int i) {
                System.out.println("总大小:"+pContentLength+"已上传:"+pBytesRead);
            }
        });
        //处理乱码问题(自己加的小插件)
        upload.setHeaderEncoding("utf-8");
        //设置单个文件最大值
        upload.setFileSizeMax(1024*1024*10);
        //设置总共上传文件的大小
        //1024=1kb*1024=1m*10=10m
        upload.setSizeMax(1024*2024*10);

        return  upload;
    }
    public static String uploadPareRequest(ServletFileUpload upload, HttpServletRequest req, String uploadPath) throws IOException, FileUploadException {



        String msg="";
        //3.处理上传文件
        //把前端请求解析,封装成一个FileItem对象 需要从ServletFileLoad中获取
        List<FileItem> fileItems = upload.parseRequest(req);
        for (FileItem fileItem : fileItems) {
            //判断文件上传的是普通的表单还是带文件的表单
            if(fileItem.isFormField()){
                //getFileName指的是前端单控件的name;
                String name = fileItem.getFieldName();
                String value = fileItem.getString("utf-8");
                System.out.println(name+":"+value);
            }else {//文件表单的话
                //============================处理文件=============================//
                String uploadFileName = fileItem.getName();
                //可能存在名字不合法的情况
                if(uploadFileName.trim().equals("")||uploadFileName==null){
                    continue;
                }
                //获得上传文件的名字  最后一个/的后面就是url的上传的文件名字
                String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/")+1);
                //获得上传文件的后辍名   最后一个点的后面就是后辍名样式
                String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".")+1);

                //如果文件名后辍不是我们所需要的类型 return  告诉用户类型不对

                //可以使用UUID(唯一识别同行码),保证文件名统一
                //UUID.randoUUID() 随机生成一个识别码
                //网络传输的东西都需要序列化
                //pojo  实体类 如果要在多个电脑运行  传输==》需要把对象序列化了

                //implement Serializable :标记接口,JVM---->java栈  本地方法栈  native---》C++
                String uuidPath = UUID.randomUUID().toString();
                //============================存放地址=============================//
                //存到哪里
                //文件真实路径
                String realPath =uploadPath+"/"+uuidPath;
                //给每个文件创建一个文件夹
                File realPathFile = new File(realPath);
                if(!realPathFile.exists()){
                    realPathFile.mkdir();
                }
                //============================文件传输=============================//
                //获得输入的流
                InputStream inputStream = fileItem.getInputStream();
                //创建一个文件输出流
                //reaPath=真实的文件夹
                //差了一个文件;加上输出文件的名字+“/”+uuidPath
                FileOutputStream fos = new FileOutputStream(realPathFile + "/" + fileName);

                //创建缓冲区
                byte[] buffer = new byte[1024 * 1024];

                //判断是否读取完毕
                int len=0;
                //如果大于0  说明还有数据
                while ((len=inputStream.read(buffer))>0){
                    fos.write(buffer,0,len);
                }
                //关闭流
                fos.close();
                inputStream.close();
                msg="文件上传成功";
                fileItem.delete();//上传成功消除临时文件

            }
        }
        return msg;
    }
}
4.配置xml
  <servlet>
    <servlet-name>FileDown</servlet-name>
    <servlet-class>com.ws.File.FileDown</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>FileDown</servlet-name>
    <url-pattern>/upload.do</url-pattern>
  </servlet-mapping>
5.查看上传的文件

我们设置的WEB-INF文件夹里面
直接在里面查看就可以看到

6.来源

1.狂神视频学习
2.如果错误请指出改正
3.本人刚刚入门有些知识不是很专业望理解

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值