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();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            //清空response
            response.reset();
            //设置response的Header
            String filenameString = new String(filename.getBytes("gbk"),"iso-8859-1");
            response.addHeader("Content-Disposition", "attachment;filename=" + filenameString);
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }

	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 getFilePath() {
		return filePath;
	}

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

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	private static final Logger log = Logger
			.getLogger(AjaxFileUploadAction.class);
	private static final long serialVersionUID = 1L;
}

4、struts配置

<struts> 
   <package name="struts_Ajax_code" extends="json-default"> 
       <!-- 文件上传 -->  
       <action name="fileAction" class="com.bk.eserver.web.action.AjaxFileUploadAction" method="fileUpload"> 
            <result type="json" name="success"> 
                 <param name="contentType">text/html</param> 
            </result> 
       </action> 
   </package>  
   <package name="struts_Jsp_code" extends="struts-default"> 
       <!-- 图片读取 -->  
       <action name="redImage" class="com.bk.eserver.web.action.AjaxFileUploadAction" method="readImg"> 
            <result type="stream"> 
                 <param name="contentType">application/octet-stream</param>  
                 <param name="inputName">inputStream</param>  
                 <param name="contentDisposition">attachment;filename=${fileName}</param>  
                 <param name="bufferSize">4096</param> 
            </result> 
       </action>  
       <!-- 文件下载 -->  
       <action name="downloadImage" class="com.bk.eserver.web.action.AjaxFileUploadAction" method="download"> 
            <result type="stream"> 
                 <param name="contentType">application/octet-stream</param>  
                 <param name="inputName">inputStream</param>  
                 <param name="contentDisposition">attachment;filename=${fileName}</param>  
                 <param name="bufferSize">4096</param> 
            </result> 
       </action> 
   </package> 
</struts>




本文转载:CSDN博客