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

时间:2021-12-24 00:15:34

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

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

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

微博:伊直都在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. &lbrack;原创&rsqb;java WEB学习笔记75:Struts2 学习之路-- 总结 和 目录

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

  2. &lbrack;原创&rsqb;java WEB学习笔记66:Struts2 学习之路--Struts的CRUD操作&lpar; 查看 &sol; 删除&sol; 添加&rpar; 使用 paramsPrepareParamsStack 重构代码 ,PrepareInterceptor拦截器,paramsPrepareParamsStack 拦截器栈

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

  3. &lbrack;原创&rsqb;java WEB学习笔记95:Hibernate 目录

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

  4. Java NIO 学习笔记(五)----路径、文件和管道 Path&sol;Files&sol;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&plus;CSS学习笔记 &lpar;6&rpar; - 开始学习CSS

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

  9. Lua学习笔记4&period; coroutine协同程序和文件I&sol;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. oracle 空值与 null

    Oracle中的空字符串基本上是被当成空NULL来处理的,我们可以从下面的得到印证. select nvl('','NULL') from dual          返回 'NULL' select ...

  2. Dim Loop 出现结果不同

    (1)结果是:循环1次 Dim counter,num counter = 0 'num = 9 Do Until num = 10     num = num - 1     counter = c ...

  3. &lbrack;转&rsqb; 强大的python字符串解析

    1.python字符串通常有单引号('...').双引号("...").三引号("""...""")或('''...'' ...

  4. IoC in Spring

    写两个关于Spring中使用IoC的小例子,一个是半动态创建Bean,另一个是全动态创建Bean,它们适合不同的应用场景. 一.半动态:在一个实际项目中遇到过这样的问题,项目组开发的某个系统具备在LE ...

  5. PL&sol;SQL集合 ----- varrays

    varrays可以再表,记录,对象定义中使用,类似于C中的数组. 1.定义varrays用作PL/SQL程序构造块. declare type integer_varray ) of integer; ...

  6. codeforces 462div&period;2

    A A Compatible Pair standard input/output 1 s, 256 MB    x1916 B A Prosperous Lot standard input/out ...

  7. topcoder srm 580 div1

    problem1 link 最优选择一定是在$2n$个端点中选出两个. problem2 link 分开考虑每个区间.设所有区间的左端点的最大值为$lc$,所有区间的右端点的最小值为$rc$.对于某个 ...

  8. 169&period; Majority Element &lpar;Array&rpar;

    Given an array of size n, find the majority element. The majority element is the element that appear ...

  9. U盘安装OSX

    1.插入U盘,磁盘工具,格式化U盘为Mac OS X拓展 (日志式): 2.去网站搜索recovery disk assistant,此文件大约1.1M,直接打开使用它制作启动盘,进度条完毕就完成了. ...

  10. 使用Postman对Restful接口进行测试

    趁着项目需要,花了两天时间对postman进行了一下学习,因为看到各大测试群,各个初入测试的孩子们都在问postman,但其实网上也有很多的教程,这里我就再来发一篇. 1. Http协议 要对接口进行 ...