基于struts2的ajaxfileupload异步上传插件的使用

实例:

jsp页面

<%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!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">
<title>文件上传</title>
<link rel="stylesheet"
	href="${pageContext.request.contextPath }/js/AjaxFileUploaderV2.1/ajaxfileupload.css">
<script type="text/javascript"
	src="${pageContext.request.contextPath }/js/AjaxFileUploaderV2.1/jquery.js"></script>
<script type="text/javascript"
	src="${pageContext.request.contextPath }/js/AjaxFileUploaderV2.1/ajaxfileupload.js"></script>
<script type="text/javascript">
	function FormSubmit() {
		var file = $("#file").val();
		if (file == "") {
			alert("请选择文件");
			return;
		}
		var fileType = file.substring(file.lastIndexOf(".") + 1);
		if (fileType != "docx" && fileType != "doc") {
			alert("上传文件格式错误");
			return;
		}
		var url = "${pageContext.request.contextPath}/struts2_upload.action?nowtime="
				+ new Date().getTime();
		$.ajaxFileUpload({
			url : url,
			secureuri : false,
			fileElementId : "file", //file的id 
			dataType : 'json',//返回值类型 一般设置为json
			success : function(data, status) {
				alert(data.message);
			}
		});
	}
</script>
</head>
<body>
	<div>
		<form
			action="${pageContext.request.contextPath }/struts2_upload.action"
			method="post" enctype="multipart/form-data">
			<p>
				<label>请选择上传文件:</label><input type="file" name="file" id="file">
			</p>
			<p>
				<input type="button" value="提交" onclick="FormSubmit();" />
			</p>
		</form>
	</div>
</body>
</html>

Action代码

package org.zsm.learn.struts2.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport {

	private static final long serialVersionUID = -1063647163701747470L;

	// 与上传文件相关的三个参数
	private File file;
	private String fileFileName;
	private String fileContentType;
	// Action相关参数的设置
	private String savePath;
	private long maximumSize;
	private String allowedTypes;

	// 返回结果
	private Map<String, Object> result;

	public Map<String, Object> getResult() {
		return result;
	}

	public String upload() {
		result = new HashMap<String, Object>();
		// 判断上传文件是否符合要求
		if (getFile() == null) {
			result.put("success", false);
			result.put("messages", "上传文件不能为空!!!");
		} else if (!validateUploadLength(maximumSize)) {
			result.put("success", false);
			result.put("message", "上传文件超出了限制!!!");
		} else if (!validateUploadType(allowedTypes)) {
			result.put("success", false);
			result.put("message", "上传文件类型不符合要求!!!");
		} else {
			// 获取存储上传目录
			String storageDir = ServletActionContext.getServletContext()
					.getRealPath(savePath);
			// 判断存储上传目录
			File storageFile = new File(storageDir);
			if (!storageFile.exists()) {
				storageFile.mkdirs();
			}
			// 上传文件
			File destFile = generateDestFile(storageDir, fileFileName);
			uploadFile(destFile, file);
			result.put("success", true);
			result.put("message", "文件上传成功!!!");
		}
		return "success";
	}
	
	public String ActionError(){
		result = new HashMap<String, Object>();
		result.put("success", false);
		result.put("messages", "上传文件超过了限制的大小");
		return "actionError";
	}
	
	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public File generateDestFile(String destFileDir, String sourceFileName) {
		File destDir = new File(destFileDir);
		if (!destDir.exists()) {
			destDir.mkdirs();
		}
		// 生成规则
		return new File(destDir, sourceFileName);
	}

	public static void uploadFile(File destFile, File sourceFile) {
		InputStream input = null;
		OutputStream output = null;
		try {
			input = new FileInputStream(sourceFile);
			output = new FileOutputStream(destFile);
			IOUtils.copy(input, output);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(output);
			IOUtils.closeQuietly(input);
		}
	}

	/**
	 * 判断是否支持上传文件的类型
	 * 
	 * @param types
	 * @return
	 */
	public boolean validateUploadType(String types) {
		String[] allowedTypes = null;
		// 获取文件上传类型
		String fileType = getFileContentType();
		allowedTypes = types.split(",");
		for (String type : allowedTypes) {
			if (type.equals(fileType)) {
				return true;
			}
		}
		return false;
	}

	public boolean validateUploadLength(long maximumSize) {
		if (getFile().length() > maximumSize) {
			return false;
		}
		return true;
	}

	public String getSavePath() {
		return savePath;
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	public long getMaximumSize() {
		return maximumSize;
	}

	public void setMaximumSize(long maximumSize) {
		this.maximumSize = maximumSize;
	}

	public String getAllowedTypes() {
		return allowedTypes;
	}

	public void setAllowedTypes(String allowedTypes) {
		this.allowedTypes = allowedTypes;
	}
}

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>
	<!-- <constant name="struts.custom.i18n.resources" value="ApplicationResources" 
		/> -->
	<package name="default" extends="json-default">
	   <action name="struts2_*" class="org.zsm.learn.struts2.action.FileUploadAction"
		method="{1}">
		 <param name="savePath">/upload</param>
		 <param name="maximumSize">1048576</param>
		 <param name="allowedTypes">
			application/vnd.ms-powerpoint,application/msword
		 </param>
		<!-- 注意结合Action观察struts.xml中result的配置。 contentType参数是一定要有的,
		否则浏览器总是提示将返回的JSON结果另存为文件,不会交给ajaxfileupload处理。这是因 
		为struts2 JSON Plugin默认的contentType为application/json,
		而ajaxfileupload则要求为text/html。 -->
		<result name="success" type="json">
		  <param name="contentType">
			text/html
		  </param>
		  <param name="root">result</param>
		</result>
		<result name="actionError" type="json">
	          <param name="root">result</param>
		  <param name="contentType">
			text/html
		</param>
		</result>
		<result name="input" type="redirect">struts2_ActionError.action</result>
	</action>
	</package>
</struts>

转载于:https://my.oschina.net/u/1425545/blog/296617

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值