Struts2之上传与下载

Struts2之上传与下载

  • 1、文件上传
    • 1.1、commons-fileupload组件
    • 1.2、单文件上传
    • 1.3、多文件上传
    • 1.4、文件下载
      • 1.4.1、Stream结果类型
      • 1.4.2、下载实例

1、文件上传

1.1、commons-fileupload组件

Commons是Apache开放源代码组织的一个Java子项目,其中的FileUpload是用来处理HTTP文件上传的子项目。

组件特点:

  • 使用简单:可以方便地嵌入到JSP文件中,编写少量的代码即可完成文件的上传功能。
  • 能够全程控制上传的内容。
  • 能够对上传文件的大小、类型进行控制。

注意:在Struts2中,struts-core依赖已经包含commons-fileupload组件的相关依赖,所以在struts2的项目中无需额外再导入commons-fileupload组件的相关依赖。

1.2、单文件上传

(1)页面

创建上传页面upload.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传页面title>
head>
<body>
     <form action="upload.action" method="post" enctype="multipart/form-data">
           <div>
               <label>选择文件:label>
               <input type="file" name="upload"/>
           div><br>
           <div>
               <input type="submit" value="点击上传" />
           div>
     form>
body>
html>

注意:form表单必须设置enctype="multipart/form-data"属性且提交方式为post。

创建success.jsp页面,为上传成功后的跳转页面。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="s" uri="/struts-tags" %>
DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>success!title>
head>
<body>
   <h1>文件上传成功!h1>
body>
html>

(2)Action控制器

创建上传控制器UploadAction,在Action控制器中需要提供3个成员变量:文件、文件类型、文件名称。如下:

public class UploadAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	
	// 文件对象,与name值保持一致
	private File upload;
	
	// 文件类型,为name属性值 + ContentType
	private String uploadContentType;
	
	// 文件名称,为name属性值 + FileName
	private String uploadFileName;

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	
	/**
	 * 
	 * @Title: uploadByIO   
	 * @Description: IO流上传
	 * @Author: yanchengzhi   
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	public String uploadByIO() {
		showFileInfo();
		String path = "E:/upload";
		InputStream in = null;
		OutputStream on = null;
		try {
			in = new FileInputStream(upload);
			on = new FileOutputStream(path + "/" + uploadFileName);
			IOUtils.copy(in, on);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
				on.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return SUCCESS;
	}
	
	/**
	 * 简单方式上传
	 * @Title: uploadSimple   
	 * @Description: TODO(描述这个方法的作用)
	 * @Author: yanchengzhi   
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	public String uploadSimple() {
		showFileInfo();
		String path = "E:/upload";
		String realPath = path + File.separator +uploadFileName;
		try {
			FileUtils.copyFile(upload, new File(realPath));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	private void showFileInfo() {
		System.out.println("文件大小:" + upload.length() / 1024 + "KB");
		System.out.println("文件名称:" + uploadFileName);
		System.out.println("文件类型:" + uploadContentType);
	}

}

(3)struts.xml配置

在这里插入图片描述

             <package name="upload" extends="default">
                  <action name="upload" class="com.ycz.struts01.action.UploadAction" method="uploadSimple">
                        <result>/success.jspresult>
                  action>
             package>

注意:如果要上传的文件大小超过2M,需要配置最大文件限制,否则上传会出错。

(4)测试

启动项目,访问http://localhost:8081/struts01/upload.jsp:

Struts2之上传与下载_第1张图片
选择文件上传,点击上传按钮,页面跳转:

Struts2之上传与下载_第2张图片
控制台打印:

Struts2之上传与下载_第3张图片
查看E盘下的upload目录:

Struts2之上传与下载_第4张图片
文件上传成功。

1.3、多文件上传

多文件上传和单文件上传本质上是一样的,只不过Action里单文件是用对象接收,而多文件是用数组来接收的,直接在上面的基础上进行修改。

(1)修改upload.jsp页面

     <form action="upload.action" method="post" enctype="multipart/form-data">
           <div>
               <label>选择文件一:label>
               <input type="file" name="upload"/>
           div><br>
           <div>
               <label>选择文件二:label>
               <input type="file" name="upload"/>
           div><br>
           <div>
               <label>选择文件三:label>
               <input type="file" name="upload"/>
           div><br>
           <div>
               <input type="submit" value="点击上传" />
           div>
     form>

(2)修改UploadAction控制器

public class UploadAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	
	// 文件
	private File[] upload;
	
	// 文件类型
	private String[] uploadContentType;
	
	// 文件名称
	private String[] uploadFileName;
	
	public File[] getUpload() {
		return upload;
	}

	public void setUpload(File[] upload) {
		this.upload = upload;
	}

	public String[] getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String[] uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String[] getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String[] uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	/**
	 * 
	 * @Title: uploadByIO   
	 * @Description: IO流上传
	 * @Author: yanchengzhi   
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	public String uploadByIO() {
		String path = "E:/upload";
		InputStream in = null;
		OutputStream on = null;
		for(int i=0;i<upload.length;i++) {
			try {
				in = new FileInputStream(upload[i]);
				on = new FileOutputStream(path + "/" + uploadFileName);
				IOUtils.copy(in, on);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					in.close();
					on.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}	
		}
		return SUCCESS;
	}
	
	/**
	 * 简单方式上传
	 * @Title: uploadSimple   
	 * @Description: TODO(描述这个方法的作用)
	 * @Author: yanchengzhi   
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	public String uploadSimple() {
		String path = "E:/upload";
		for(int i=0;i<upload.length;i++) {
			String realPath = path + File.separator +uploadFileName[i];
			try {
				FileUtils.copyFile(upload[i], new File(realPath));
			} catch (Exception e) {
				e.printStackTrace();
			}	
		}
		return SUCCESS;
	}
	
}

(3)测试

启动项目,访问http://localhost:8081/struts01/upload.jsp:

Struts2之上传与下载_第5张图片
选择多个文件点击上传,页面跳转:

Struts2之上传与下载_第6张图片
查看E盘upload目录:

Struts2之上传与下载_第7张图片
多文件上传成功。

1.4、文件下载

1.4.1、Stream结果类型

Struts2之上传与下载_第8张图片

1.4.2、下载实例

下载上面上传成功的文件。

(1)down.jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>下载页面title>
head>
<body>
    <a href="download.action?fileName=人间美食客.xmind">人间美食客.xmind下载a><br>
    <a href="download.action?fileName=设计文档.docx">设计文档.docx下载a><br>
body>
html>

(2)DownAction控制器

public class DownloadAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	
	// 输入流,读取文件
	private InputStream inputStream;
	
	// 文件名称
	private String fileName;

	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 download() {
		try {
			String path = "E:/upload/" + fileName;
			// 设置中文编码
			fileName = URLEncoder.encode(fileName, "UTF-8");
			// 初始化流
			inputStream = new BufferedInputStream(new FileInputStream(path));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

}

(3)struts.xml配置

             <package name="download" extends="default">
                  <action name="download" class="com.ycz.struts01.action.DownloadAction" method="download">
                       <result name="success" type="stream">
                              
                              <param name="contentType">application/octet-streamparam>
                              
                              <param name="inputName">inputStreamparam>
                              
                              <param name="contentDisposition">attachment;filename="${fileName}"param>
                              
                              <param name="bufferSize">4096param>
                       result>
                  action>
             package>

注意:在result里需要配置下载类型,指定流对象,设置下载形式,设置缓冲区大小等。

(4)测试

启动项目,访问http://localhost:8081/struts01/down.jsp页面:

Struts2之上传与下载_第9张图片
分别点击两个下载链接:

Struts2之上传与下载_第10张图片
Struts2之上传与下载_第11张图片

你可能感兴趣的:(Struts2框架,struts,java,servlet)