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

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

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

微博:伊直都在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>

 

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

  1. [原创]java WEB学习笔记75:Struts2 学习之路-- 总结 和 目录

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  2. [原创]java WEB学习笔记66:Struts2 学习之路--Struts的CRUD操作( 查看 / 删除/ 添加) 使用 paramsPrepareParamsStack 重构代码 ,PrepareInterceptor拦截器,paramsPrepareParamsStack 拦截器栈

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  3. [原创]java WEB学习笔记95:Hibernate 目录

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  4. Java NIO 学习笔记(五)----路径、文件和管道 Path/Files/Pipe

    目录: Java NIO 学习笔记(一)----概述,Channel/Buffer Java NIO 学习笔记(二)----聚集和分散,通道到通道 Java NIO 学习笔记(三)----Select ...

  5. Java后台处理框架之struts2学习总结

    Java后台处理框架之struts2学习总结 最近我在网上了解到,在实际的开发项目中struts2的使用率在不断降低,取而代之的是springMVC.可能有很多的朋友看到这里就会说,那还不如不学str ...

  6. 学习笔记:CentOS7学习之二十:shell脚本的基础

    目录 学习笔记:CentOS7学习之二十:shell脚本的基础 20.1 shell 基本语法 20.1.1 什么是shell? 20.1.2 编程语言分类 20.1.3 什么是shell脚本 20. ...

  7. 学习笔记:CentOS7学习之十九:Linux网络管理技术

    目录 学习笔记:CentOS7学习之十九:Linux网络管理技术 本文用于记录学习体会.心得,兼做笔记使用,方便以后复习总结.内容基本完全参考学神教育教材,图片大多取材自学神教育资料,在此非常感谢MK ...

  8. HTML+CSS学习笔记 (6) - 开始学习CSS

    HTML+CSS学习笔记 (6) - 开始学习CSS 认识CSS样式 CSS全称为"层叠样式表 (Cascading Style Sheets)",它主要是用于定义HTML内容在浏 ...

  9. Lua学习笔记4. coroutine协同程序和文件I/O、错误处理

    Lua学习笔记4. coroutine协同程序和文件I/O.错误处理 coroutine Lua 的协同程序coroutine和线程比较类似,有独立的堆栈.局部变量.独立的指针指令,同时又能共享全局变 ...

  10. 学习笔记:CentOS7学习之二十五:shell中色彩处理和awk使用技巧

    目录 学习笔记:CentOS7学习之二十五:shell中色彩处理和awk使用技巧 25.1 Shell中的色彩处理 25.2 awk基本应用 25.2.1 概念 25.2.2实例演示 25.3 awk ...

随机推荐

  1. 【转】const 是左结合的,若左边为空,则再向右结合

    const 是左结合的,若左边为空,则再向右结合 一.指向  const  对象的指针指向  const  对象的指针,指的是指针指向的对象的内容是const的,不可修改,但指针本身(即指针的值)是可 ...

  2. java正则表达式取括号里面的内容

    public static String changeCompName(String compName){ String NewCompName=""; //cm1230NHL6X ...

  3. json格式的转换为json字符串函数

    function toJSON(object){ var type = typeof object; if ('object' == type) { if (Array == object.const ...

  4. CC2540 USB Dongle 使用说明

    CC2540做的USB Dongle可以烧写不同的固件从而做很多PC端的应用,下面我们来介绍下下载固件的方法和一些典型应用: 下载接口: 3V3引脚连接到CC Debugger的Target Volt ...

  5. NRF51822之GPIOTE介绍

    Note This library is obsolete and should not be used in new designs. Instead, you should use GPIOTE ...

  6. ios 消息传递机制

    引用文章 一.KVO 1.当对象中的某个属性值发生了改变,可以对这些值的观察者做出通知. 2.接受者(会接收到值发生改变的消息) 必须知道发送者(值将发生改变的那个对象). 3.接收者同样还需要知道发 ...

  7. mysql case when用法

    SELECT CASE WHEN `categoryid` =1THEN '参赛队员'ELSE '指导老师'END FROM `blog_article` WHERE 1

  8. Activity初步,初学者必看

    Activity是什么? Activity是一个可与用户交互并呈现组件的视图.通俗说就是运行的程序当前的这个显示界面. 如果你还不明白,那么你写过HTML吗,它就好比一个网页.我们程序中的用户视图,都 ...

  9. PIVOT&UNPIVOT

    如果是家电销售员,那么可能需要统计每月日销售的彩电.冰箱.空调...最大值.最小值.平均值等 如果你是耳鼻喉科医生,那么可能需要统计月度年度日接客咽炎.喉炎.鼻炎...最大值.最小值.平均值等 如果你 ...

  10. 网页中的超链接<a>标签

    格式: <a href="目标网址" title="鼠标滑过显示的文本">链接显示的文本</a> 注意:为文本加入<a>标签 ...