这两天支撑另外一个项目组,需要修改两个功能页面,其中涉及到要做ajax异步上传图片,在网上找了不少资料,但是发现ajaxfileupload.js在返回json对象时会给json结果加一个<pre></pre>框.使得返回结果对json的解析不正确,这样就会出现网上大多数人出现的,ajax请求总是返回到error里面,并且报异常。后来找js高手帮忙修改ajaxfileupload.js文件后完成该功能。
实现步骤:
重点是先修改ajaxfileupload.js文件:
if ( type == "json" )
var str = r.responseText.toString();
return str.substring(str.indexOf("{"),str.indexOf("}")+1)
jsp页面
<script type="text/javascript" src="*/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="*/ajaxfileupload.js"></script>
<input id="file" name="file" domName="图片信息" type="file" class="txt w250" οnchange="ajaxFileUpload(this)"></input>
<input type="hidden" id="imageUrl" name="imageUrl" value=""/>
js:
后台处理接收数据时需要配置struts.xml文件单独配置function ajaxFileUpload(obj){ var tmpFilePath = obj.value; alert(obj.value); if(validateImage(obj)) { $.ajaxFileUpload( { url: $("#contextPathId").val() + "/broadband/fileUploadAction.action?num="+Math.random(), //需要链接到服务器地址 secureuri:false, fileElementId:'file', //文件选择框的id属性 dataType: 'json', //服务器返回的格式,可以是json success: function (json) //服务器成功响应处理函数 { json = jQuery.parseJSON(json); //jquery解析Json对象 document.getElementById("imageUrl").value=json.data; alert("文件上传成功");//从服务器返回的json中取出message中的数据,其中message为在struts2中定义的成员变量 }, error: function (data,status,e)//服务器响应失败处理函数 { alert("文件上传失败"); } }); } } function validateImage(obj) { var file = obj; var tmpFileValue = file.value; //校验图片格式 if(/^.*?\.(gif|png|jpg|jpeg|bmp)$/.test(tmpFileValue.toLowerCase())){ return true; } else { alert("只能上传jpg、jpeg、png、bmp或gif格式的图片!"); return false; } }
action处理方法:<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="struts-fileupload" extends="json-default" namespace="/broadband"> <action name="fileUploadAction" class="com.sxit.web.broadband.action.BroadbandAction" method="uploadImage"> <result type="json" name="success"> <param name="contentType">text/html</param> </result> <result type="json" name="error"> <param name="contentType">text/html</param> </result> </action> </package> </struts>
private File file; //注意file名与表单name对应 private String fileFileName; //file+FileName为固定写法,否则取不到 private String fileContentType; //file+ContentType为固定写法 /*** * 上传图片信息 * @return * @throws Exception */ public String uploadImage() throws Exception{ String path = SystemConfig.getFrontHotModelPath(); System.out.println(path+"============================="); File file = new File(path); // JSON消息 JSONMessage msg = new JSONMessage(); if(!file.exists()){ file.mkdirs(); } File f = this.getFile(); if(this.getFileFileName().endsWith(".exe")){ this.message="上传文件格式不正确,请重新选择!"; msg.setSuccess(false); msg.setMessage("上传文件格式不正确,请重新选择!"); return ERROR; } FileInputStream inputStream = new FileInputStream(f); String filename=System.currentTimeMillis() + "." +FilenameUtils.getExtension(this.getFileFileName()); FileOutputStream outputStream = new FileOutputStream(path+"images/Broadband/big/"+ filename); byte[] buf = new byte[1024]; int length = 0; while ((length = inputStream.read(buf)) != -1) { outputStream.write(buf, 0, length); } this.setFileUrl("../images/Broadband/big/"+ filename); msg.setSuccess(true); msg.setMessage("上传文件成功!"); msg.setData(this.getFileUrl()); inputStream.close(); outputStream.flush(); super.getRequest().setCharacterEncoding("UTF-8"); super.getResponse().setCharacterEncoding("UTF-8"); super.getResponse().getWriter().println(msg.toJSONObject()); return SUCCESS; } setter和getter
加上ss2h框架和json解析以及需要的js文件。