ajax无刷新上传(使用ajaxfileupload.js)
2015-08-06 12:39
591 查看
<body> <input type="file" id="files" name="files" onchange="javascript: ajaxFileUpload()" class="transparent_class"/> <input type="button" value="上传" /> <p><img id="img1" alt="上传成功啦" src="" width="135px" height="101px"/></p> </body> <script type="text/javascript"> $(function () { $(":button").click(function () { ajaxFileUpload(); }) }) function ajaxFileUpload() { $.ajaxFileUpload ( { url: '${ctx}/ajaxUploadFile.html', //用于文件上传的服务器端请求地址 secureuri: false, //是否需要安全协议,一般设置为false fileElementId: 'files', //文件上传域的ID dataType: 'json', //返回值类型 一般设置为json success: function (data, status) //服务器成功响应处理函数 { /*alert(data); //可以查看返回的值* $("#img1").attr("src","${ctx }/upload/" + data); if (typeof (data.error) != 'undefined') { if (data.error != '') { alert(data.error); } else { alert(data.msg); } } }, error: function (data, status, e)//服务器响应失败处理函数 { $("#img1").attr("src", "${ctx }/images/pictureFile.jpg"); alert(e); } } ) return false; } </script>
mvc后台:
controller:
package com.langtai.controller; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import com.alibaba.fastjson.JSON; import com.langtai.service.UploadService; @Controller public class UploadController { @Autowired UploadService UploadService; @RequestMapping(value="ajaxUploadFile.html" , method=RequestMethod.POST) public void AjaxUpload(@RequestParam MultipartFile[] files, HttpServletResponse response, HttpServletRequest request) throws IOException{ System.out.println("收到" + files.length + "个上传的请求"); //WEB-INF/upload在服务器中默认的地址 String realPath = request.getSession().getServletContext().getRealPath("/upload"); List<String> fileNames = UploadService.upload(files, realPath); String jsonFileNames = JSON.toJSONString(fileNames); System.out.println(jsonFileNames); PrintWriter out = response.getWriter(); out.print(jsonFileNames); out.flush(); out.close(); } }
service:
package com.langtai.service; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.commons.io.FileUtils; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; @Service public class UploadService { public List<String> upload(MultipartFile[] files,String realPath) { //上传的文件的原名 String originalFilename = null; List<String> fileNames = new ArrayList<String>(); int i = 0; for (MultipartFile multipartFile : files) { if(multipartFile.getSize()==0) continue; originalFilename = multipartFile.getOriginalFilename(); System.out.println("文件的原名:" + originalFilename); System.out.println("文件的名称:" + multipartFile.getName()); System.out.println("文件的长度:" + multipartFile.getSize()); System.out.println("文件的类型:" + multipartFile.getContentType()); System.out.println("=============================================="); try { String[] Filetype = originalFilename.split("\\."); String newFileName = new Date().getTime() + (i++) + "." + Filetype[Filetype.length-1]; fileNames.add(newFileName); FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), new File(realPath, newFileName)); } catch (IOException e) { System.out.println("文件" + originalFilename + "上传失败,堆栈轨迹如下:"); e.printStackTrace(); } } return fileNames; } }
------------------------------------------------------------------------------------------------------------------------------------------
该插件对于json的处理有误,解析json会出错,所以:
修改源码,将
if ( type == "json" )
eval_r( "data = " + data );
改成:
if ( type == "json" ){
data = jQuery.parseJSON(jQuery(data).text());
}
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
在1.4以上jq中没有了handleError这个函数,所以可以把这个函数添加进这个插件中最上面去:
handleError: function (s, xhr, status, e) { if (s.error) { s.error.call(s.context || s, xhr, status, e); } if (s.global) { (s.context ? jQuery(s.context) : jQuery.event).trigger("ajaxError", [xhr, s, e]); } }, httpData: function (xhr, type, s) { var ct = xhr.getResponseHeader("content-type"), xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0, data = xml ? xhr.responseXML : xhr.responseText; if (xml && data.documentElement.tagName == "parsererror") throw "parsererror"; if (s && s.dataFilter) data = s.dataFilter(data, type); if (typeof data === "string") { if (type == "script") jQuery.globalEval(data); if (type == "json") data = window["eval"]("(" + data + ")"); } return data; },
------------------------------------------------------------------------------------------------------------------------------------------
在使用这个插件的时候,<input>中一定要有name属性和id属性,且name属性要和controller中参数名一样。
相关文章推荐
- webservice 实现json模式
- js 常用方法
- js 请求URL 追加参数
- JavaScript 之 SeaJS 学习
- [Javascript] 对象的创建与类的封装
- JavaScript之数据类型
- JS实现弹出浮动窗口(支持鼠标拖动和关闭)实例详解
- JavaScript之数据类型
- JavaScript键码表
- JS学习-原型链的理解
- javascript 获取标签内的内容
- js中如何将GBK的英文转为普通英文, 全角转为半角
- 使用javascript的onsubmit进行表单合法性验证
- 原生JS实现轮播图
- Highmaps的天津地图数据JSON格式
- 用js来实现页面的换肤功能(带cookie记忆)
- Extjs换肤+cookie皮肤记忆功能
- JavaScript淡入淡出渐变简单实例
- 原生js绑定和解除事件
- js闭包类似cs闭包