wuheng преди 2 години
родител
ревизия
b1924f2ee2

BIN
day15/demo.xlsx


+ 50 - 0
day15/pom.xml

@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+
+    <groupId>org.example</groupId>
+    <artifactId>day15</artifactId>
+    <version>1.0</version>
+
+
+
+<!--
+  IO 磁盘读写 需要用到 IO
+  表单是二进制流, 不能用一般的接受参数取处理 上传文件流
+  -->
+
+    <dependencies>
+
+        <dependency>
+            <groupId>javax.servlet</groupId>
+            <artifactId>javax.servlet-api</artifactId>
+            <version>4.0.1</version>
+        </dependency>
+        <dependency>
+            <groupId>commons-io</groupId>
+            <artifactId>commons-io</artifactId>
+            <version>2.11.0</version>
+        </dependency>
+        <dependency>
+            <groupId>commons-fileupload</groupId>
+            <artifactId>commons-fileupload</artifactId>
+            <version>1.4</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.apache.poi</groupId>
+            <artifactId>poi</artifactId>
+            <version>5.2.2</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.apache.poi</groupId>
+            <artifactId>poi-ooxml</artifactId>
+            <version>5.2.2</version>
+        </dependency>
+
+    </dependencies>
+
+</project>

+ 74 - 0
day15/src/main/java/com/lovecoding/download/DownloadAction.java

@@ -0,0 +1,74 @@
+package com.lovecoding.download;
+
+import org.apache.commons.io.IOUtils;
+
+import javax.servlet.ServletOutputStream;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.net.URLEncoder;
+
+@WebServlet("/downloadFile")
+public class DownloadAction extends HttpServlet {
+
+    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+
+        /**
+         * 正常的情况下 ,  下载是不走Java逻辑代码的
+         * 我们下载文件都交给 Tomcat, 文件是静态资源, Http 服务器 (Tomcat, Nginx ) 都能处理
+         * 我们不用管 文件下载的事情
+         * 特俗情况, 付费下载, 统计文件下载数量, 管控下载流量
+         */
+
+        /**
+         * 一般情况下, 管控文件下载需要 Token !
+         * 我们改需要 文件名
+         * 我们使用 Java 管控文件下载 不一定非要 使用Java IO去处理文件
+         * 301 跳转
+         */
+
+        /**
+         * 一般情况下 我们需要把文件重命名, 或者加随即时间戳
+         * 总之呢  尽可能不让用户猜到文件路径, 方案有很多
+         * 用户使用的是一个映射文件名  "abc.pdf" => "202030517-abc.pdf"
+         * 用户可能上传 攻击脚本
+         */
+
+        req.setCharacterEncoding("UTF-8");
+        String fileName = req.getParameter("filename");
+
+        if ( fileName == null || fileName.equals("") ) {
+            resp.setContentType("text/html; charset=utf-8");
+            resp.getWriter().print("请携带文件名访问");
+            return ;
+        }
+        //取存储文件的文件夹路径
+        String filePath = req.getServletContext().getRealPath("") + "uploads";
+        //取拼接文件名
+        String file = filePath + File.separator + fileName;
+        //判断文件是否存在
+        File file1 = new File(file);
+        if ( !file1.exists() ) {
+            resp.setContentType("text/html; charset=utf-8");
+            resp.getWriter().print("<h1>文件不存在</h1>");
+            return ;
+        }
+        //文件转文件流
+        FileInputStream fileInputStream = new FileInputStream(file1);
+        //取相应流
+        ServletOutputStream outputStream = resp.getOutputStream();
+        //向浏览器声明下载
+        resp.addHeader("content-type", "application/octet-stream");
+        //声明文件名
+        String downloadFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
+        resp.addHeader("content-disposition", "attachment; filename*=UTF-8''" + downloadFileName);
+        //将文件的文件流和resp相应流合并输出
+        IOUtils.copy( fileInputStream, outputStream );
+    }
+
+
+}

+ 43 - 0
day15/src/main/java/com/lovecoding/execel/ExecelAction.java

@@ -0,0 +1,43 @@
+package com.lovecoding.execel;
+
+import org.apache.poi.ss.usermodel.CellType;
+import org.apache.poi.xssf.usermodel.XSSFCell;
+import org.apache.poi.xssf.usermodel.XSSFRow;
+import org.apache.poi.xssf.usermodel.XSSFSheet;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+
+public class ExecelAction {
+    public static void main(String[] args) throws IOException {
+        //我们表格文件存储地址
+        String path = "day15/demo.xlsx";
+        //我们创建一个表格的文件流
+        FileInputStream fileInputStream = new FileInputStream(path);
+        //创建XSSFWorkbook 对象
+        XSSFWorkbook sheets = new XSSFWorkbook(fileInputStream);
+        //我们要设置我们读取的Sheet
+        XSSFSheet sheet = sheets.getSheetAt(0);
+        //获取Execel表格行数
+        int lastRowNum = sheet.getLastRowNum();
+        //循环表格的每一行
+        for (int i = 0; i < lastRowNum; i++) {
+            //获取到表的一行
+            XSSFRow row = sheet.getRow(i);
+            //取这一样有多少列
+            short lastCellNum = row.getLastCellNum();
+            //循环每一列
+            for (int j = 0; j < lastCellNum; j++) {
+                //具体取每一个单元格
+                XSSFCell cell = row.getCell(j);
+                //设置转换类型
+                cell.setCellType(CellType.STRING);
+                //获取单元格数据
+                String stringCellValue = cell.getStringCellValue();
+                //打印单元格数据
+                System.out.println( stringCellValue );
+            }
+        }
+    }
+}

+ 67 - 0
day15/src/main/java/com/lovecoding/upload/UploadAction.java

@@ -0,0 +1,67 @@
+package com.lovecoding.upload;
+
+
+import org.apache.commons.fileupload.FileItem;
+import org.apache.commons.fileupload.FileItemFactory;
+import org.apache.commons.fileupload.FileUpload;
+import org.apache.commons.fileupload.FileUploadException;
+import org.apache.commons.fileupload.disk.DiskFileItemFactory;
+
+import javax.servlet.ServletException;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+
+@WebServlet("/uploadFile")
+public class UploadAction extends HttpServlet{
+
+    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+        resp.setContentType("text/html; charset=utf-8");
+        req.setCharacterEncoding("UTF-8");
+        if (!FileUpload.isMultipartContent( req )) {
+            resp.getWriter().print("请使用上传表单域");
+            return ;
+        }
+        //创建文件存储工具类
+        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
+        //创建上传工具类
+        FileUpload fileUpload = new FileUpload(diskFileItemFactory);
+        try {
+            //把request对象交给FileUplad工具类处理 得到的是一个列表 存储的是表单字段
+            List<FileItem> fileItems = fileUpload.parseRequest(req);
+            //我们循环每个表单字段
+            for ( FileItem fileItem : fileItems ) {
+                //我们只处理 文件上传
+                if ( !fileItem.isFormField() ) {
+                    //拼接保存文件的路径
+                    String realPath = req.getServletContext().getRealPath("") + "uploads";
+                    //通过File对象创建路径
+                    File file1 = new File(realPath);
+                    //如果路径不存在则创建
+                    if ( !file1.exists() ) {
+                        //创建文件夹
+                        file1.mkdirs();
+                    }
+                    //拼接文件名
+                    String path = realPath + File.separator + fileItem.getName();
+                    System.out.println(path);
+                    //撞见文件File实例
+                    File file = new File(path);
+                    //保存文件
+                    fileItem.write(file);
+                }
+            }
+            resp.getWriter().print("文件上传成功!!");
+        } catch (FileUploadException e) {
+            e.printStackTrace();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+    }
+
+}

+ 6 - 0
day15/web/WEB-INF/web.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
+         version="4.0">
+</web-app>

+ 16 - 0
day15/web/index.jsp

@@ -0,0 +1,16 @@
+<%--
+  Created by IntelliJ IDEA.
+  User: 武恒
+  Date: 2023/2/17
+  Time: 9:14
+  To change this template use File | Settings | File Templates.
+--%>
+<%@ page contentType="text/html;charset=UTF-8" language="java" %>
+<html>
+  <head>
+    <title>$Title$</title>
+  </head>
+  <body>
+  $END$
+  </body>
+</html>

+ 33 - 0
day15/web/upload.jsp

@@ -0,0 +1,33 @@
+<%--
+  Created by IntelliJ IDEA.
+  User: 武恒
+  Date: 2023/2/17
+  Time: 9:14
+  To change this template use File | Settings | File Templates.
+--%>
+<%@ page contentType="text/html;charset=UTF-8" language="java" %>
+<html>
+<head>
+    <title>上传文件</title>
+</head>
+<body>
+
+
+<div style="width: 500px; margin: 0 auto;" >
+
+    <form method="post" action="<%=request.getContextPath()%>/uploadFile" enctype="multipart/form-data">
+
+        <input type="file" name="file" /> <br />
+
+        <input type="text" name="username" value="张三" />
+
+        <input type="text" name="age" value="18" />
+
+        <button type="submit">提交</button>
+
+    </form>
+
+</div>
+
+</body>
+</html>