ajax文件上传
需求:
通过ajax异步方式上传图片,上传成功后做些操作
实现:
js部分:
引入:
<script src="http://js.linkrmb.com/ajax/jquery.upload.js" type="text/javascript"> </script>
代码:
function doUpload() { // 上传方法 $.upload({ // 上传地址 url: '${basePath}upload/img', // 文件域名字 fileName: 'filedata', // 上传完成后, 返回json, text dataType: 'json', // 上传之前回调,return true表示可继续上传 onSend: function() { return true; }, // 上传之后回调 onComplate: function(data) { $("#imgurl").val(data.msg.url); $("#imgname").val(data.msg.id); } }); }
html部分:
<tr> <td width="10%" > 封面图片: </td> <td width="90%"> <input id="imgname" name="imgname" type="text" readonly="readonly" > <input type="button" onclick="doUpload()" value="点击上传图片"> <input id="imgurl" name="imgurl" type="hidden" > </td> </tr>
java部分:
@RequestMapping(value = "/img", method = RequestMethod.POST) @ResponseBody public UploadResVo img(HttpServletRequest request) throws Exception { UploadResVo resVo = new UploadResVo(); MsgVo msg = new MsgVo(); String file = processImg(request, "imageDir"); msg.setId(file); msg.setLocalname(file); msg.setUrl(url); resVo.setMsg(msg); return resVo; } private String processImg(HttpServletRequest request,String imageDir) throws Exception { String uuid = CommonUtils.getUUID(); request.setCharacterEncoding("UTF-8"); DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8")); } else { System.out.println("上传文件的大小:" + item.getSize()); System.out.println("上传文件的类型:" + item.getContentType()); System.out.println("上传文件的名称:" + item.getName()); String file = imageDir + File.separator +uuid+"."+ FilenameUtils.getExtension(item.getName()); item.write(new File(file)); return uuid+"."+ FilenameUtils.getExtension(item.getName()); } } return uuid; }
相关推荐
kentrl 2020-11-10
结束数据方法的参数,该如何定义?-- 集合为自定义实体类中的结合属性,有几个实体类,改变下标就行了。<input id="add" type="button" value="新增visitor&quo
ajaxyan 2020-11-09
zndy0 2020-11-03
学留痕 2020-09-20
Richardxx 2020-11-09
learningever 2020-09-19
chongxiaocheng 2020-08-16
ajaxhe 2020-08-16
lyqdanang 2020-08-16
curiousL 2020-08-03
TONIYH 2020-07-22
时光如瑾雨微凉 2020-07-19
83510998 2020-07-18
坚持着执着 2020-07-16
jiaguoquan00 2020-07-07
李永毅 2020-07-05
坚持着执着 2020-07-05