`
空指针异常
  • 浏览: 21563 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类

Jquery插件ajaxfileupload应用

阅读更多
官网地址:http://www.phpletter.com/Demo/AjaxFileUpload-Demo/

ajaxfileupload重复上传问题:
http://www.cnblogs.com/zerojevery/p/3897294.html

说明:结合struts2
1.JSP.
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link type="text/css" href="ajaxfileupload/ajaxfileupload.css">
<script type="text/javascript" src="jquery/jquery.js"></script>
<script type="text/javascript" src="ajaxfileupload/ajaxfileupload.js"></script>
<script type="text/javascript">
function ajaxFileUpload(obj) {
	if (validateAttache(obj)) {
		$("#loading")
		.ajaxStart(function(){
			$(this).show();
		})
		.ajaxComplete(function(){
			$(this).hide();
		});

		$.ajaxFileUpload({
					url : 'uploadAction!upload.action',// 用于文件上传的服务器端请求地址
					secureuri : false,// 一般设置为false
					fileElementId : 'file',// 文件上传空间的id属性 <input type="file"
					dataType : 'json',// 返回值类型 一般设置为json
					success : function(data, status) // 服务器成功响应处理函数
					{
						alert('success');
					},
					error : function(data, status, e) {// 服务器响应失败处理函数
						alert('failurdde' + data);
					}
				})
		return false;
	}
}

function validateAttache(obj) {
	var file = obj;
	var tmpFileValue = file.value;
	// 校验图片格式
	if (/^.*?\.(rar|zip|apk|udg)$/.test(tmpFileValue.toLowerCase())) {
		return true;
	} else {
		$.messager.alert('提示', '只能上传rar、zip、udg或apk格式的附件!', 'error');
		return false;
	}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body>
	<input type="text" id="fileUploadTextId" name="fileUploadTextName" readonly /> 
	<a href="javascript:void(0)" onclick="file.click();">浏览...</a> 
	<input type="file" id="file" onchange="return ajaxFileUpload(this);" name="file" style="display: none"/>
	<img id="loading" src="ajaxfileupload/loading.gif" style="display:none;">
</body>
</html>


2.Action
package com.utstar.action;

import java.io.File;
import java.io.IOException;

import org.apache.struts2.convention.annotation.Action;

@Action(value = "uploadAction")
public class UploadAction {

	private static final UploadConfig config = UploadConfig.getInstance();

	private File file;
	private String fileFileName;
	private String fileFileContentType;

	public void upload() {
		try {
			// 文件保存路径
			String targetDirVal = config.getFilePath();
			if (!targetDirVal.endsWith("/")) {
				targetDirVal += "/";
			}

			File targetDir = new File(targetDirVal);
			if (!targetDir.exists()) {
				targetDir.mkdirs();
			}

			File targetFile = new File(targetDirVal + fileFileName);
			if (!targetFile.exists()) {

				targetFile.createNewFile();

			}
			FileUtil.copyFile(this.file, targetFile);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//return "success";
	}

	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 getFileFileContentType() {
		return fileFileContentType;
	}

	public void setFileFileContentType(String fileFileContentType) {
		this.fileFileContentType = fileFileContentType;
	}
}


UploadConfig.java
package com.utstar.action;

import java.util.Properties;

/**
 *
 */
public class UploadConfig {
	private volatile static UploadConfig singleton;
	private static final String FILENAME = "attachment.properties";
	private Properties props = null;
	
	//upload to linux
	private String filePath = "/attachments";
	
	private UploadConfig() {
		props = new Properties();
		try {
			this.props.load(this.getClass().getClassLoader()
					.getResourceAsStream(FILENAME));
			
			this.filePath = props.getProperty("ABSOLUTE_SERVER_UPLOAD_FILE_PATH");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static UploadConfig getInstance() {
		if (singleton == null) {
			synchronized (UploadConfig.class) {
				if (singleton == null) {
					singleton = new UploadConfig();
				}
			}
		}
		return singleton;
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}
}


FileUtil
package com.utstar.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 文件操作工具
 *
 */
public class FileUtil {
	// 复制文件
	public static void copyFile(File sourceFile, File targetFile)
			throws IOException {
		BufferedInputStream inBuff = null;
		BufferedOutputStream outBuff = null;
		try {
			// 新建文件输入流并对它进行缓冲
			inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

			// 新建文件输出流并对它进行缓冲
			outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

			// 缓冲数组
			byte[] b = new byte[1024 * 5];
			int len;
			while ((len = inBuff.read(b)) != -1) {
				outBuff.write(b, 0, len);
			}
			// 刷新此缓冲的输出流
			outBuff.flush();
		} finally {
			// 关闭流
			if (inBuff != null)
				inBuff.close();
			if (outBuff != null)
				outBuff.close();
		}
	}

	/**
	 * 
	 * @param filepath
	 * @throws IOException
	 */
	public static void del(String filepath) throws IOException {
		File f = new File(filepath);// 定义文件路径
		if (f.exists() && f.isDirectory()) {// 判断是文件还是目录
			if (f.listFiles().length == 0) {// 若目录下没有文件则直接删除
				f.delete();
			} else {// 若有则把文件放进数组,并判断是否有下级目录
				File delFile[] = f.listFiles();
				int i = f.listFiles().length;
				for (int j = 0; j < i; j++) {
					if (delFile[j].isDirectory()) {
						del(delFile[j].getAbsolutePath());// 递归调用del方法并取得子目录路径
					}
					delFile[j].delete();// 删除文件
				}
			}
		}
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics