1. 上官网 http://www.uploadify.com/下载flash版本的uploadify压缩包。解压缩到WEB-INF/resources/里面。
2. 写后台
package com.lj.cms.dto; /** * 专门用来返回Ajax * @author Administrator * */ public class AjaxObj { /** * 0表示失败, 1表示成功 */ private int result; /** * 提示消息 */ private String message; /** * 附加对象, 用来存储一些特定的返回信息 */ private Object obj; public int getResult() { return result; } public void setResult(int result) { this.result = result; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Object getObj() { return obj; } public void setObj(Object obj) { this.obj = obj; } public AjaxObj() { this.result=1; } public AjaxObj(int result, String message, Object obj) { this.result = result; this.message = message; this.obj = obj; } public AjaxObj(int result, String message) { this.result = result; this.message = message; } public AjaxObj(int result) { super(); this.result = result; } }
/** * 返回AjaxObj对象 。 * @return * @throws IOException */ @RequestMapping("/upload") //返回的是json类型的值, 而uplodify只能接受字符串 public @ResponseBody AjaxObj upload(MultipartFile attach) throws IOException{ System.out.println(attach.getOriginalFilename()); return new AjaxObj(1); }
这里返回的是text类型的文件, jsp页面中要将其转换成json格式。
3. 写一个upload.jsp文件,如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <link rel="stylesheet" type="text/css" href="<%=path%>/resources/uploadify/uploadify.css" /> <script type="text/javascript" src="<%=path%>/resources/js/jquery-1.9.0.js"></script> <script type="text/javascript" src="<%=path%>/resources/uploadify/jquery.uploadify.js"></script> <script type="text/javascript"> $(function() { var path = $("#ctx").val(); $("#attach").uploadify({ swf : path + "/resources/uploadify/uploadify.swf", uploader : "upload", fileObjName : "attach", height : 30, width : 120, auto:false, fileSizeLimit:'50MB', fileTypeExts:"*.jpg;*.avi;*.wmv;*.txt;*.doc", onUploadSuccess:function(file,data,response){ var ao=$.parseJSON(data); if(ao.result==1){ alert("文件 "+file.name+" 成功上传");} } }); $("#upload").click(function(){ $("#attach").uploadify("upload","*"); }); // console.log($.ajax("upload")); }); </script> </head> <body> <input type="hidden" id="ctx" value="<%=path%>"> <input type="file" id="attach" value="" /> <input type="button" id="upload" value="点击上传"> </body> </html>
这里要导入jquery, uploadify的js和css文件。