工具---文件上传工具的使用

1 、jsp

<%--   表单中有文件上传输入项时,表单的enctype属性必须设置为multipart/form-data --%>
<form action="${pageContext.request.contextPath}/upload.do" method="post" enctype="multipart/form-data">

    <input type="text" name="user">     <br>
    <input type="file" name="file1">    <br>
    <input type="file" name="file2">    <br>
    <input type="submit" > <input type="reset"> <br>
</form>

表单中有文件上传输入项时,表单的enctype属性必须设置为multipart/form-data

2 、依赖包

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</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>


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


    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.3</version>
    </dependency>

3 、servlet

文件上传必须使用post方法

public class FileServlet 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 tempPath = this.getServletContext().getRealPath("/WEB-INF/temp");
        File tempFile = new File(tempPath);
        if (!tempFile.exists()) {
            tempFile.mkdir();  //创建目录
        }

        //处理上传的文件,一般要通过流的方式来获取,可以使用req.getInputStream(),但比较麻烦
        //建议使用文件上传组件实现,common-fileupload,需要依赖于commons-io组件
        try {
        // 1  创建DiskFileItemFactory对象,处理文件上传路径、大小限制
        DiskFileItemFactory factory = getDiskFileItemFactory(tempFile);

        // 2  获取ServletFileUpload
        ServletFileUpload upload = getServletFileUpload(factory);

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

            req.setAttribute("msg", msg);
            req.getRequestDispatcher("info.jsp").forward(req,resp);

        } catch (FileUploadException e) {
            e.printStackTrace();
        }


    }

    public static DiskFileItemFactory getDiskFileItemFactory(File file) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024 * 1024);    //缓存区大小
        factory.setRepository(file);        //临时文件保存的路径
        return factory;
    }

    public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) {
        ServletFileUpload upload = new ServletFileUpload(factory);
        //监听文件上传进度
        upload.setProgressListener(new ProgressListener() {
            @Override
            public void update(long l, long l1, int i) {
                System.out.println("总大小: " + l1 + " 已上传: " + l);
            }
        });

        upload.setHeaderEncoding("utf-8");
        upload.setFileSizeMax(1024 * 1024 * 10); //单个文件大小 10M
        return upload;
    }

    public static String uploadParseRequest(ServletFileUpload upload, HttpServletRequest request, String uploadPath) throws IOException, FileUploadException {

        String msg = "";
        //把前端的请求解析,封装成fileItem对象(需要从获取ServletFileUpload对象获取)

        List<FileItem> fileItems = upload.parseRequest(request);
        for (FileItem fileItem : fileItems) {
            //判断表单是否是带文件的表单
            if (fileItem.isFormField()) {    //不是文件表单
                String uploadFieldName = fileItem.getFieldName();
                String value = fileItem.getString("utf-8");
                System.out.println(uploadFieldName + ":" + value);
            } else {     //是文件表单
                //###########################  处理文件  ########################################//
                String uploadFieldName = fileItem.getName();
                if (uploadFieldName == null || uploadFieldName.trim().equals("")) {   //文件名不合法
                    continue;
                }
                //获得上传的文件名
                String fileName = uploadFieldName.substring(uploadFieldName.lastIndexOf("/") + 1);
                //获得上传的文件的后缀名
                String fileEnd = uploadFieldName.substring(uploadFieldName.lastIndexOf(".") + 1);
                System.out.println("文件名" + fileName + "文件类型" + fileEnd);

                String uuidPath = UUID.randomUUID().toString();
                //###########################  存放地址  ########################################//
                String realPath = uploadPath + "/" + uuidPath;
                File file = new File(realPath);
                if (!file.exists()) {
                    file.mkdir();
                }
                //###########################  文件传输  ########################################//
                InputStream inputStream = fileItem.getInputStream();
                FileOutputStream fileOutputStream = new FileOutputStream(realPath + "/" + fileName);
                byte[] buffer = new byte[1024 * 1024];
                int len = 0;

                while ((len = inputStream.read(buffer)) > 0) {
                    fileOutputStream.write(buffer, 0, len);
                }
                fileOutputStream.close();
                inputStream.close();
                msg = "文件上传成功";
                fileItem.delete();  //上传成功,清除临时文件
            }
        }
        return msg;

    }

}

记得在web.xml中注册servlet

3 、上传位置

maven项目会上传到tomcat–>webapps–>ROOT–>WEB-INF
空项目会上传到输出文件夹中
在这里插入图片描述

posted @ 2022-02-10 19:54  ︶ㄣ演戲ㄣ  阅读(1)  评论(0编辑  收藏  举报  来源