日期:2014-05-16  浏览次数:20591 次

java文件上传--基于ajaxFileUpload+struts2

jQuery插件ajaxFileUpload可以实现ajax文件上传,使用非常简单。

下面做一个简单的demo(以上传图片为例),实现图片上传,图片显示,图片下载

注:以下的代码是在项目的基础上进行开发。css样式文件、包路径等未做修改。

1、 ajaxFileUpload文件下载地址http://www.phpletter.com/Demo/AjaxFileUpload-Demo/

2、自行引入jquery.js、ajaxFileUpload.js文件

jsp核心代码:

<script type="text/javascript">
  function fileUpload() {
	$.ajaxFileUpload( {
		url : 'admin/fileAction.do',//用于文件上传的服务器端请求地址
		secureuri : false,          //一般设置为false
		fileElementId : 'file',     //文件上传空间的id属性  <input type="file" id="file" name="file" />
		dataType : 'json',          //返回值类型 一般设置为json
		success : function(data, status) {
			$("#downImg").show();   //待上传成功后 显示下载按钮
			$("#downImg").attr("href","admin/downloadImage.do?filePath="+data.filePath);
			$("#showImg").attr("src","admin/redImage.do?path=" + data.filePath);
		}
	})
  }
</script>
<table class="editTable">
   <tr>
	<td colspan="4">
		<img id="showImg" alt="" src="">
		<a id="downImg" style="display: none" href="">下载</a> 
	</td>
   </tr>
   <tr>
	<td class="title">
		上传图片:
	</td>
	<td colspan="3">
		<input type="file" id="file" name="file" onchange="fileUpload();">
	</td>
   </tr>
</table>

3、AjaxFileUploadAction

public class AjaxFileUploadAction extends WebSupport {

	private File file;            //文件
	private String fileFileName;  //文件名 
	private String filePath;      //文件路径
	private InputStream inputStream;

	/**
	 * 图片上传
	 * 
	 * @return
	 */
	public String fileUpload() {
		String path = ServletActionContext.getServletContext().getRealPath("/upload");
		File file = new File(path); // 判断文件夹是否存在,如果不存在则创建文件夹
		if (!file.exists()) {
			file.mkdir();
		}
		try {
		  if (this.file != null) {
			File f = this.getFile();
			String fileName = java.util.UUID.randomUUID().toString(); // 采用时间+UUID的方式随即命名
			String name = fileName+ fileFileName.substring(fileFileName.lastIndexOf(".")); // 保存在硬盘中的文件名

			FileInputStream inputStream = new FileInputStream(f);
			FileOutputStream outputStream = new FileOutputStream(path+ "\\" + name);
			byte[] buf = new byte[1024];
			int length = 0;
			while ((length = inputStream.read(buf)) != -1) {
				outputStream.write(buf, 0, length);
			}
			inputStream.close();
			outputStream.flush();
			//文件保存的完整路径  比如:D:\tomcat6\webapps\eserver\\upload\a0be14a1-f99e-4239-b54c-b37c3083134a.png
			filePath = path+"\\"+name;

		  }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 用于图片页面显示
	 * 
	 * @return
	 */
	public String readImg() {
		try {
			inputStream = new FileInputStream(new File(getRequest().getParameter("path")));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	/**
	 * 图片下载
	 * @return
	 */
	public String download() {
        String path = filePath;
        HttpServletResponse response = ServletActionContext.getResponse();
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            S