javaweb-07-fileUpload

1、新建一个空项目

2、空项目什么都没有,在项目中新建Module,添加web;

3、配置 Tomcat

4、导包

  • common-fileupload

  • common-io

5、index.jsp

<body>

<%--
  post:上传文件大小没有限制,一定要选择 post 上传
--%>
<form action="${pageContext.request.contextPath}/upload.do" method="post" enctype="multipart/form-data">
  <p>上传用户:<input type="text" name="username"></p>
  <p><input type="file" name="filename"></p>
  <p><input type="file" name="filename2"></p>
  <p><input type="submit" value="提交"> | <input type="reset" value="重置"></p>
</form>

</body>

表单中如果包含一个文件上传项的话,这个表单的entype属性必须设置为multipart/form-data

浏览器的表单类型为multipart/form-data的话,服务器想获取数据就要通过流

6、FileServlet.java

public class FileServlet extends HttpServlet {

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

        try {

            //判断上传的表单是普通表单还是带文件的表单
            if (!ServletFileUpload.isMultipartContent(request)) {
                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/tmp");
            File TmpFile = new File(tmpPath);
            if (!TmpFile.exists()) {
                TmpFile.mkdir();
            }

            // 1、创建DiskFileItemFactory对象,处理文件路径或者大小限制
            DiskFileItemFactory factory = getDiskFileItemFactory(TmpFile);
            // 2、获取ServletFileUpload
            ServletFileUpload upload = getServletFileUpload(factory);
            // 3、处理上传文件
            String msg = uploadParseRequest(upload, request, uploadPath);

            request.setAttribute("msg", msg);
            request.getRequestDispatcher("/info.jsp").forward(request, response);
        }catch (FileUploadException e){
            e.printStackTrace();
        }

    }


    public static DiskFileItemFactory getDiskFileItemFactory(File file) {
        //1、获取磁盘对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 通过这个工厂设置一个缓冲区,当上传的文件大于这个缓冲区的时候,将他放到临时文件中;
        factory.setSizeThreshold(1024 * 1024);// 缓冲区大小为1M
        factory.setRepository(file);// 临时目录的保存目录
        return factory;
    }


    public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) {
        //2、获取上传文件的解析对象
        ServletFileUpload upload = new ServletFileUpload(factory);

        // 监听上传进度
        upload.setProgressListener(new ProgressListener() {
            public void update(long pBytesRead, long pContentLength, int pItems) {
                System.out.println("总大小:" + pContentLength + "已上传:" + pBytesRead+",进度:"+((double)pBytesRead/pContentLength)*100+"%");
            }
        });

        upload.setHeaderEncoding("UTF-8");
        // 设置单个文件的最大值
        upload.setFileSizeMax(1024 * 1024 * 10);

        return upload;
    }


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

        //3、正式解析表单中上传的文件,并将其存储在服务器上指定的位置
        String msg = "";

        // 把前端请求解析,封装成FileItem对象
        List<FileItem> fileItems = upload.parseRequest(request);
        for (FileItem fileItem : fileItems) {
            if (fileItem.isFormField()) {// 判断上传的文件是普通的表单还是带文件的表单
                // getFieldName指的是前端表单控件的name;
                String name = fileItem.getFieldName();
                String value = fileItem.getString("UTF-8");
                System.out.println(name + ": " + value);
            } else {//上传的文件

                // ===============================处理文件===============================
                // 拿到文件名
                String uploadFileName = fileItem.getName();
                System.out.println("上传的文件名: " + uploadFileName);
                if (uploadFileName.trim().equals("") || uploadFileName == null) {
                    continue;
                }

                String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
                String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
                /*
                 * 如果文件后缀名fileExtName不是我们所需要的 就直按return.不处理,告诉用户文件类型不对。
                 */
                System.out.println("文件信息[件名: " + fileName + " ---文件类型" + fileExtName + "]");
                // 可以使用UUID(唯一识别的通用码),保证文件名唯
                // UUID. randomUUID(),随机生一个唯一识别的通用码;
                String uuidPath = UUID.randomUUID().toString();

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

                //============================文件传输============================
                // 获得文件上传的流
                InputStream inputStream = fileItem.getInputStream();
                // 创建一个文件输出流
                // realPath = 真实的文件夹;
                // 差了一个文件;加上翰出文件的名产"/"+uuidFileName
                FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName);

                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = inputStream.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }

                // 关闭流
                fos.close();
                inputStream.close();

                msg = "文件上传成功!";
                fileItem.delete(); // 上传成功,清除临时文件
            }

        }
        return msg;
    }

}

7、web.xml

8、info.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
${msg}
</body>
</html>

启动Tomcat ,测试!

然后打开 Project Structure---Artifacts---查看 Output directory 路径,我们上传的文件就在里面!

posted @ 2021-10-19 16:03  比特风  阅读(44)  评论(0)    收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示