Struts2(3)——文件上传下载

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_45044097/article/details/102585068

1 上传下载案例

课堂案例:图片的上传,下载
在这里插入图片描述
注意:config文件夹是resources(File–Project Structure–Modules)
在这里插入图片描述

  1. 新建Moven项目
    pom.xml中添加依赖包
    (在这里面去去找包,复制代码:https://mvnrepository.com/)
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.struts/struts2-core -->
    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts2-core</artifactId>
      <version>2.5.14.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.struts/struts2-json-plugin -->
    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts2-json-plugin</artifactId>
      <version>2.5.14.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

配置好你的Tomcat昂…
2. 首先编写一个index.jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
        <form action="user/uploadFile.action"  method="post" enctype="multipart/form-data">
                <input type="file" name="headImg">
            <button>上传头像</button>
        </form>
</body>
</html>

展示页面show.jsp,点击上传的图片可进行下载:

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <a href="user/downFile.action?path=${path}">
        <img src="${path}">
    </a>
</body>
</html>
  1. index.jsp页面中必须使用post提交,并且需要enctype属性,然后配置struts.xml来响应这个请求,和处理普通请求的配置一模一样:
<struts>
        <package name="user" namespace="/user" extends="struts-default">
            <action name="uploadFile" class="com.cn.control.UploadFileAction" method="upload">
                <result name="success" type="redirect">/show.jsp</result>
            </action>
               <!-- 下载-->
            <action name="downFile" class="com.cn.control.DownFileAction" method="down">
                <result name="success" type="stream">
                    <param name="inputName">inputStream</param>
                    <param name="contentDisposition">attachment;fileName=${fileName}</param>
                    <param name="bufferSize">1024</param>
                </result>
            </action>
        </package>
</struts>
  1. 最后完成Action类的编写,主要是生成一个file的对象,还有struts2要求必须的文件名属性,给两个属性添加set方法,然后在execute方法中,通过FileUtils工具类,完成文件的上传。
    UploadFileAction.java
    (getter,setter方法很重要啊)
public class UploadFileAction extends ActionSupport {
    //固定,跟页面的name一致的
   private File headImg;//  File  []  headImg
   private String headImgFileName; //获得文件的名字File[]  headImgFileName
   public String upload() throws IOException {
        System.out.println(headImg);
        System.out.println(headImgFileName);
        //项目发布路径
        //获得上下文本对象
        ServletContext servletContext = ServletActionContext.getServletContext();
        //获得项目发布路径
        String realPath = servletContext.getRealPath("img");
        //获取文件的名字
        String fileName = UUIDUtil.getFileName(headImgFileName);
        System.out.println(fileName);
        //拷贝
        FileUtils.copyFile(headImg, new File(realPath,fileName));
        //要回显  保存路径
        HttpSession session = ServletActionContext.getRequest().getSession();
        session.setAttribute("path","img/"+fileName);
      /*  try {
            //直接拷贝  盘符中
            FileUtils.copyFile(headImg,new  File("D:/",headImgFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        return SUCCESS;
    }
    public void setHeadImg(File headImg) {
        this.headImg = headImg;
    }
    public void setHeadImgFileName(String headImgFileName) {
        this.headImgFileName = headImgFileName;
    }
}

DownFileAction.java

public class DownFileAction extends ActionSupport {
    // 用户提供的地址(与前端)
    private String path;
    // 响应给用户  流 文件  文件名
    private InputStream inputStream;
    private String fileName;
    public String getPath() {
        return path;
    }
    public void setPath(String path) {
        this.path = path;
    }
    public InputStream getInputStream() {
        return inputStream;
    }
    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }
    public String getFileName() {
        return fileName;
    }
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
    public String down() throws FileNotFoundException {
        // 看文件是否存在
        String realPath = ServletActionContext.getServletContext().getRealPath(path);
        // 文件对象
        File file = new File(realPath);
        if(file.exists()) {
            inputStream = new FileInputStream(file);
            fileName = path.substring(path.lastIndexOf("//")+1);
        }
        System.out.println(fileName);
        return SUCCESS;
    }
}
  1. 重启web服务器,测试上传功能。在Struts2中,有一个默认的上传限制,默认只能上传2097152字节,也就是2M的内容,如果上传大于2M的内容将会报找不到上传文件对象的错误,如果要上传更大的文件,需要修改参数配置。

2 POI操作

自学吧,到处都有大佬的博客学习!然后写个demo熟悉一下…

详细说明 参考文章:https://www.cnblogs.com/huajiezh/p/5467821.html

Apache POI是Apache软件基金会的开源项目,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。 .NET的开发人员则可以利用NPOI (POI for .NET) 来存取 Microsoft Office文档的功能。

2.1 包名称说明

HSSF提供读写Microsoft Excel XLS格式档案的功能。
XSSF提供读写Microsoft Excel OOXML XLSX格式档案的功能。
HWPF提供读写Microsoft Word DOC格式档案的功能。
HSLF提供读写Microsoft PowerPoint格式档案的功能。
HDGF提供读Microsoft Visio格式档案的功能。
HPBF提供读Microsoft Publisher格式档案的功能。
HSMF提供读Microsoft Outlook格式档案的功能。

2.2 POI常用类说明

类名 说明
HSSFWorkbook Excel的文档对象
HSSFSheet Excel的表单
HSSFRow Excel的行
HSSFCell Excel的格子单元
HSSFFont Excel字体
HSSFDataFormat 格子单元的日期格式
HSSFHeader Excel文档Sheet的页眉
HSSFFooter Excel文档Sheet的页脚
HSSFCellStyle 格子单元样式
HSSFDateUtil 日期
HSSFPrintSetup 打印
HSSFErrorConstants 错误信息表

2.3 POI对Excel的基本操作

POI依赖:

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>3.17</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-scratchpad</artifactId>
      <version>3.17</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>3.17</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml-schemas</artifactId>
      <version>3.17</version>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>23.0</version>
    </dependency>

别人写的操作Excel工具包,参考一下:
https://www.cnblogs.com/dzpykj/p/8417738.html

2.4 POI对Word的基本操作

(1)POI操作Word简介
POI读写Excel功能强大、操作简单。但是POI操作时,一般只用它读取word文档,POI只能能够创建简单的word文档,相对而言POI操作时的功能太少。

(2)POI创建Word文档的简单示例

XWPFDocument doc = new XWPFDocument();// 创建Word文件
XWPFParagraph p = doc.createParagraph();// 新建一个段落
p.setAlignment(ParagraphAlignment.CENTER);// 设置段落的对齐方式
p.setBorderBottom(Borders.DOUBLE);//设置下边框
p.setBorderTop(Borders.DOUBLE);//设置上边框
p.setBorderRight(Borders.DOUBLE);//设置右边框
p.setBorderLeft(Borders.DOUBLE);//设置左边框
XWPFRun r = p.createRun();//创建段落文本
r.setText("POI创建的Word段落文本");
r.setBold(true);//设置为粗体
r.setColor("FF0000");//设置颜色
p = doc.createParagraph();// 新建一个段落
r = p.createRun();
r.setText("POI读写Excel功能强大、操作简单。");
XWPFTable table= doc.createTable(3, 3);//创建一个表格
table.getRow(0).getCell(0).setText("表格1");
table.getRow(1).getCell(1).setText("表格2");
table.getRow(2).getCell(2).setText("表格3");
FileOutputStream out = newFileOutputStream("d:\\POI\\sample.doc");
doc.write(out);
out.close();

(3)POI读取Word文档里的文字

FileInputStream stream = newFileInputStream("d:\\POI\\sample.doc");
XWPFDocument doc = new XWPFDocument(stream);// 创建Word文件
for(XWPFParagraph p : doc.getParagraphs()) {  //遍历段落
	System.out.print(p.getParagraphText());
}
for(XWPFTable table : doc.getTables()) {  //遍历表格
	for(XWPFTableRow row : table.getRows()) {
		for(XWPFTableCell cell : row.getTableCells()) {
			System.out.print(cell.getText());
		}
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_45044097/article/details/102585068