[原创]java WEB学习笔记72:Struts2 学习之路-- 文件的上传下载,及上传下载相关问题

本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用

内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系。

本人互联网技术爱好者,互联网技术发烧友

微博:伊直都在0221

QQ:951226918

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

1.文件上传

  1)表单需要注意三点:

     ① 须把 HTML 表单的 enctype 属性设置为 multipart/form-data

       ②须把 HTML 表单的method 属性设置为 post

     ③需添加 <input type=“file”> 字段. 

  2)Struts2 的文件上传实际使用的是Common FileUpload 组件,导入jar包。commons-fileupload / commons-io

  3)Struts2 进行文件上传需要使用FileUpload拦截器

  4)基本的文件操作:直接在Action 中定义如下 3个属性,并提供对应的get / set方法

       private File  [fileFieldName];    //文件对应的file 对象

     private String  [fileFieldName]ContentType; // 文件类型

     private String  [fileFieldName]pptFileName; // 文件名

  5)使用IO 流进行文件的上传

 <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <!-- 配置国际化资源文件 -->
<constant name="strut2.custom.i18n.resouce" value="i18n"></constant> <constant name="struts.action.extension" value="action,do,"></constant>
<package name="default" namespace="/" extends="struts-default"> <action name="testUpload" class="com.jason.upload.app.UploadAction">
<result>/sucess.jsp</result>
</action> </package> </struts>

struts.xml

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body> <s:form action="testUpload" method="post" enctype="multipart/form-data">
<s:file name="ppt" label="PPTfile"></s:file>
<s:textfield name="pptDesc" label="PPTDesc"></s:textfield> <s:submit></s:submit>
</s:form> </body>
</html>

upload.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body> <h4> success page</h4>
</body>
</html>

sucess.jsp

 package com.jason.upload.app;

 import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream; import javax.servlet.Servlet;
import javax.servlet.ServletContext; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class UploadAction extends ActionSupport { /**
* @Fields:serialVersionUID
*/
private static final long serialVersionUID = 1L; private File ppt;
private String pptContentType;
private String pptFileName; public File getPpt() {
return ppt;
} public void setPpt(File ppt) {
this.ppt = ppt;
} public String getPptContentType() {
return pptContentType;
} public void setPptContentType(String pptContentType) {
this.pptContentType = pptContentType;
} public String getPptFileName() {
return pptFileName;
} public void setPptFileName(String pptFileName) {
this.pptFileName = pptFileName;
} @Override
public String execute() throws Exception { ServletContext servletContext = ServletActionContext.getServletContext(); String dir = servletContext.getRealPath("/files/" + pptFileName);
System.out.println(dir); FileOutputStream out = new FileOutputStream(dir);
FileInputStream in = new FileInputStream(ppt); byte[] buffer = new byte[1024];
int len = 0;
while((len = in.read(buffer)) != -1){
out.write(buffer, 0, len);
}
out.close();
in.close(); System.out.println(ppt);
System.out.println(pptContentType);
System.out.println(pptFileName);
return SUCCESS;
} }

UploadAction.java

2.相关问题

  1)一次性上传过个文件?

   若传递多个文件,则上述3个属性,可以改为list类型,多个文件的name 属性需要一致

    

 <s:form action="testUpload" method="post" enctype="multipart/form-data">
<s:file name="ppt" label="PPTfile"></s:file>
<s:textfield name="pptDesc[0]" label="PPTDesc"></s:textfield> <s:file name="ppt" label="PPTfile"></s:file>
<s:textfield name="pptDesc[1]" label="PPTDesc"></s:textfield> <s:file name="ppt" label="PPTfile"></s:file>
<s:textfield name="pptDesc[2]" label="PPTDesc"></s:textfield> <s:file name="ppt" label="PPTfile"></s:file>
<s:textfield name="pptDesc[3]" label="PPTDesc"></s:textfield> <s:submit></s:submit>
</s:form>

  

  

     private List<File> ppts;
private String pptContentType;
private String pptFileName;

  2)对上传文件的限制?例如扩展名,内容类型,上传文件的大小?如果出错, 显示错误消息?消息可以定制?

Interceptor parameters: 

•maximumSize (optional) - the maximum size (in bytes) that the interceptor will allow a file reference to be set on the action. Note, this is not related to the various properties found in struts.properties. Default to approximately 2MB.

默认文件的最大值2M,上传的单个文件
•allowedTypes (optional) - a comma separated list of content types (ie: text/html) that the interceptor will allow a file reference to be set on the action. If none is specified allow all types to be uploaded.
允许上传的文件类型,多个使用 ',' 分割 •allowedExtensions (optional) - a comma separated list of file extensions (ie: .html) that the interceptor will allow a file reference to be set on the action. If none is specified allow all extensions to be uploaded.
允许的上传文件的类型,多个使用 ‘ , ’分割

定制文件上传错误消息

This interceptor will add several field errors, assuming that the action implements ValidationAware. These error messages are based on several i18n values stored in struts-messages.properties, a default i18n file processed for all i18n requests. You can override the text of these messages by providing text for the following keys: 

•struts.messages.error.uploading - a general error that occurs when the file could not be uploaded
文件上传出错的消息 •struts.messages.error.file.too.large - occurs when the uploaded file is too large
文件超过最大值的消息 •struts.messages.error.content.type.not.allowed - occurs when the uploaded file does not match the expected content types specified
文件内容不合法的消息 •struts.messages.error.file.extension.not.allowed - occurs when the uploaded file does not match the expected file extensions specified
文件扩展名不合法的消息

可以参考 org.apache.struts2. 下的 struts-message.properties ,可提供更多的定制信息

在 org.apache.struts2. 下的 default.properties 中有对文件上传总的大小的限制。可以使用常量的方式,修改限制:struts.multipart.maxSize = ?

  1 <!-- 配置国际化资源文件 -->
2 <constant name="strut2.custom.i18n.resouce" value="i18n"></constant>
3
4 <constant name="struts.action.extension" value="action,do,"></constant>
5
6 <package name="default" namespace="/" extends="struts-default">
7
8 <interceptors>
9 <interceptor-stack name="jasonStack">
10 <interceptor-ref name="defaultStack">
11 <param name="fileUpload.maximumSize">2000</param>
12 <param name="fileUpload.allowedTypes">text/html,text/xml</param>
13 <param name="fileUpload.allowedExtensions">html,ppt,xml</param>
14 </interceptor-ref>
15 </interceptor-stack>
16 </interceptors>
17
18
19 <default-interceptor-ref name="jasonStack"></default-interceptor-ref>
20 <action name="testUpload" class="com.jason.upload.app.UploadAction">
21 <result>/sucess.jsp</result>
22 </action>
23
24 </package>
25

struts.xml

 struts.messages.error.uploading=\u6587\u4EF6\u4E0A\u4F20\u51FA\u9519\u7684\u6D88\u606F
struts.messages.error.file.too.large=\u6587\u4EF6\u8D85\u8FC7\u6700\u5927\u503C\u7684\u6D88\u606F
struts.messages.error.content.type.not.allowed=\u6587\u4EF6\u5185\u5BB9\u4E0D\u5408\u6CD5\u7684\u6D88\u606F
struts.messages.error.file.extension.not.allowed=\u6587\u4EF6\u6269\u5C55\u540D\u4E0D\u5408\u6CD5\u7684\u6D88\u606F

i18n.properties

2.文件的下载

  1)struts2 中使用 type="stream" 的result 进行下载即可:具体细节 /struts-2.3.15.3-all/struts-2.3.15.3/docs/WW/docs/stream-result.html

  2)Struts 专门为文件下载提供了一种 Stream 结果类型. 在使用一个 Stream 结果时, 不必准备一个 JSP 页面.

  3)Stream 结果类型可以设置如下参数:(以下参数可以在Action中以 getter 方法的方式提供)

      - contentType:被下载的文件的 MIME 类型。默认值为 text/plain

      - contentLength:被下载的文件的大小,以字节为单位

      - contentDisposition: 可以设置下载文件名的ContentDispositon 响应头,默认值为 inline,通常设置为如下格式: attachment;filename="document.pdf".

      - inputName:Action 中提供的文件的输入流。默认值为 inputStream

      - bufferSize:文件下载时缓冲区的大小。默认值为 1024

      - allowCaching :文件下载时是否允许使用缓存。默认值为 true

      - contentCharSet:文件下载时的字符编码。

4)Stream 结果类型的参数可以在 Action 以属性的方式覆盖

download.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="testDownload">Down Load</a>
</body>
</html>
DownLoadAction.java
对于
contentType
contentLength
contentDisposition
inputStream
我们需要在对应的Action 中声明一个变量 且提供 getter方法
 package com.jason.upload.app;

 import java.io.FileInputStream;
import java.io.InputStream; import javax.servlet.ServletContext; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class DownLoadAction extends ActionSupport { /**
* @Fields:serialVersionUID
*/
private static final long serialVersionUID = 1L; private String contentType;
private long contentLength;
private String contentDisposition;
private InputStream inputStream; public String getContentDisposition() {
return contentDisposition;
} public long getContentLength() {
return contentLength;
} public String getContentType() {
return contentType;
} public InputStream getInputStream() {
return inputStream;
}
@Override
public String execute() throws Exception { //1.确定各成员的值
contentType = "text/html";
44 contentDisposition = "attachment;filename='a.html'";
45
46 ServletContext servletContext = ServletActionContext.getServletContext();
47 String fileName = servletContext.getRealPath("/files/a.html");
48 inputStream = new FileInputStream(fileName);
49 contentLength = inputStream.available();
return super.execute();
} }

struts.xml

 <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd"> <struts>
<action name="testDownload" class="com.jason.upload.app.DownLoadAction">
<result type="stream">
<param name="bufferSize">2048</param>
</result>
</action>
</package> </struts>

 

上一篇:oracle12c安装报错:PRVF-0002的解决方法


下一篇:Android Selinux