Struts2文件上传

提供 FileUpload 拦截器,用于解析 multipart/form-data 编码格式请求,解析上传文件的内容
fileUpload拦截器 默认在 defaultStack 栈中, 默认会执行的

	在Action需要对上传文件内容进行接收
		页面:
			<input type="file" name="upload" />
		Action :
			public class UploadAction extends ActionSupport {
				// 接收上传内容
				// <input type="file" name="upload" />
				private File upload; // 这里变量名 和 页面表单元素 name 属性一致
				private String uploadContentType;
				private String uploadFileName;
			} 
			* 格式 : 上传表单项name属性 + ContentType 、 上传表单项name属性 + FileName
			* 为三个对象 提供 setter 方法

	通过FileUtils 提供 copyFile 进行文件复制,将上传文件 保存到服务器端
	Struts2文件上传问题解决
	配置 input 视图 ,作为上传出错后 跳转页面 
	在文件上传时,如果发生错误 ,fileUpload拦截器 会设置错误信息,workflow拦截器 跳转到 input 视图

	struts.multipart.parser=jakarta 定义文件上传,采用 commons-fileupload 技术 
	 * 同时支持 cos 、pell 上传技术 (如果使用其它上传技术,单独下载jar包 )

	通过 struts.multipart.maxSize 常量设置文件上传总大小限制 
	 * struts.multipart.maxSize=2097152 默认上传文件总大小 2MB 
	 * 超过文件总大小,跳转input 视图, 通过 <s:actionError /> 回显错误信息 
	在struts.xml 设置上传总大小
	<constant name="struts.multipart.maxSize" value="20000000"></constant>

	设置上传文件总大小,对所有上传form有效,只想对当前form进行设置,可以设置fileUpload拦截器属性 
	<action name="hello5" class="com.baidu.action.Action5">
        <result >/index.jsp</result>
        <result name="input">/index.jsp</result>
        <interceptor-ref name="defaultStack">
        	<param name="fileUpload.allowedExtensions">jpg,txt</param>	<!-- 允许上传的后缀名 -->
        </interceptor-ref>
    </action>
	
	FileUpload 拦截器有 3 个属性可以设置.
		* maximumSize: 上传文件的最大长度(以字节为单位), 默认值为 2 MB
		* allowedTypes: 允许上传文件的类型, 各类型之间以逗号分隔
		* allowedExtensions: 允许上传文件扩展名, 各扩展名之间以逗号分隔
	如果针对fileUpload 进行参数设置,当出错时,在页面通过 <s:fieldError /> 回显错误信息 

	
	多文件上传
	第一步:在WEB-INF/lib下加入commons-fileupload-1.2.1.jar、commons-io-1.3.2.jar。这两个文件可以从http://commons.apache.org/下载。
	第二步:把form表的enctype设置为:“multipart/form-data“,如下:
	<form enctype="multipart/form-data" action="${pageContext.request.contextPath}/xxx.action" method="post">
	  <input  type="file" name="uploadImages">
	  <input  type="file" name="uploadImages">
	</form>
	第三步:在Action类中添加以下属性,属性红色部分对应于表单中文件字段的名称:
	public class uploadAction{
	  private File[] uploadImages;//得到上传的文件
	  private String[] uploadImagesContentType;//得到文件的类型
	  private String[] uploadImagesFileName;//得到文件的名称
	  //这里略省了属性的getter/setter方法
	  public String saveFiles() throws Exception{
			ServletContext sc = ServletActionContext.getServletContext();
			String realpath = sc.getRealPath("/uploadfile");
			try {
				if(uploadImages!=null&&uploadImages.length>0){
					 for(int i=0;i<uploadImages.length;i++){
							 File destFile = new File(realpath,uploadImageFileNames[i]);
							 FileUtils.copyFile(uploadImages[i], destFile);
					  }
				 }
			 } catch (IOException e) {
				  e.printStackTrace();}return "success";}}

	Struts2文件下载
	1) struts2 完成文件下载,通过 结果集类型 (ResultType) stream 来完成的 
		 struts-default.xml 定义 <result-type name="stream" class="org.apache.struts2.dispatcher.StreamResult"/>
	2) 使用Stream结果集 完成文件下载 
		文件下载原理:服务器读取下载文件内容,通过Response响应流写回, 设置 ContentType、 ContentDisposition 头信息

	public class StreamResult extends StrutsResultSupport {
		protected String contentType = "text/plain"; // contentType头信息  (下载文件对应 MIME协议规定类型 )
			* html --- text/html . txt--- text/plain 
		protected String contentDisposition = "inline"; // ContentDisposition头信息 (下载文件打开方式 inline浏览器内部打开, attachment 以附件形式打开)
		
		protected String inputName = "inputStream";  // 需要Action中 提供 getInputStream 方法 返回 InputStream 提供下载文件 内容 
	}	
	 
	Action 提供 InputStream  返回值 getInputStream 方法 ------- 指定下载文件流
	配置 stream 结果集 参数 <param name="contentType">${contentType}</param> ---- 在Action 中提供 getContentType
		*  ServletActionContext.getServletContext().getMimeType(filename);
	配置 stream 结果集 参数 <param name="contentDisposition">attachment;filename=${filename}</param> ---- 在Action 提供 getFilename 
		* 下载附件名乱码问题 , IE和火狐 解决不同 
		public String encodeDownloadFilename(String filename, String agent)
				throws IOException {
			if (agent.contains("Firefox")) { // 火狐浏览器
				filename = "=?UTF-8?B?"
						+ new BASE64Encoder().encode(filename.getBytes("utf-8"))
						+ "?=";
			} else { // IE及其他浏览器
				filename = URLEncoder.encode(filename, "utf-8");
			}
			return filename;
		}
		
		code:------------------------
		xml:
		<action name="download" class="com.baidu.action.DownloadAction">
		<result type="stream">
			<param name="contentType">${contentType}</param> <!-- 调用当前action中的getContentType()方法 -->
			<param name="contentDisposition">attachment;filename=${downloadFileName}</param>
			<param name="inputStream">${inputStream}</param><!-- 调用当前action中的getInputStream()方法 -->
		</result>
		</action>
		java:
		public class DownloadAction extends ActionSupport {

		private String filename; // 要下载文件的名称

		public String getFilename() {
			return filename;
		}

		public void setFilename(String filename) {
			this.filename = filename;
		}

		// 设置下载文件mimeType类型
		public String getContentType() {

			String mimeType = ServletActionContext.getServletContext().getMimeType(
					filename);
			return mimeType;
		}

		// 获取下载文件名称
		public String getDownloadFileName() throws UnsupportedEncodingException {

			return DownloadUtils.getDownloadFileName(ServletActionContext
					.getRequest().getHeader("user-agent"), filename);

		}

		public InputStream getInputStream() throws FileNotFoundException,
				UnsupportedEncodingException {

			filename = new String(filename.getBytes("iso8859-1"), "utf-8"); // 解决中文名称乱码.

			FileInputStream fis = new FileInputStream("d:/upload/" + filename);
			return fis;
		}

		@Override
		public String execute() throws Exception {
			System.out.println("进行下载....");
			return SUCCESS;
		}

	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值