利用Jquery的AjaxUpload组件实现头像异步上传并回显

来源:互联网 发布:手机网络被劫持 编辑:程序博客网 时间:2024/05/03 12:40

练习中遇到头像上传不能实时显示的问题,利用ajaxUpload异步文件上传解决。

1、导入jquery-1.10.2.min.js、ajaxupload.3.6.js包。

附ajaxupload.3.6.js下载地址:http://download.csdn.net/detail/dengchenlu/3957758

2、jsp中导入包

    <script type="text/javascript" src="${basePath }js/jquery/ajaxupload.3.6.js"></script>


2、jsp中的配置

js:

//利用AjaxUpload组件实现异步上传头像并回显    $(document).ready(function(){   var button = $("#imgButton");   new AjaxUpload(button,{   action:"${basePath}nsfw/user_ajaxUpload.action",   name:"headImg",//同Action中File文件名,""不能少   onSubmit: function(file, ext) {              if (!(ext && /^(jpg|JPG|png|PNG|gif|GIF)$/.test(ext))) {                 alert("您上传的图片格式不对,请重新选择!");                return false;              }          },         onComplete:function(file,response){//默认全成功,不再判断,直接设置img的src        var path = "${basePath}upload/";                var reg = /<pre.+?>(.+)<\/pre>/g;  var result = response.match(reg);  response = RegExp.$1;//以上三行是为了去除response返回的pre标签内容        $("#headImg").attr("src",path+response);                //由于已经异步设置了头像路径,注册时不再需要重新设置,因此直接隐藏域保存headImg属性        $("#imgHidden").val(response);        }   });    });


html:

<td class="tdBg" width="200px">头像:</td>            <td>            <img id="headImg" src="${basePath }upload/<s:property value='user.headImg'/>" width="100" height="100"/>           <input id="imgButton" type="button" name="headImg" value="上传头像" class="btn32"/> <s:hidden name="user.headImg" id="imgHidden"/>            </td>
Action中的接受配置:

//异步显示头像public void ajaxUpload(){try {//处理用户头像if(headImg != null){String filePath = ServletActionContext.getServletContext().getRealPath("upload/user");//保存路径//保存文件名 uuid+后缀String fileName = UUID.randomUUID().toString().replace("-", "")+headImgFileName.substring(headImgFileName.lastIndexOf('.'));FileUtils.copyFile(headImg,new File(filePath,fileName));String headImg = "user/"+fileName;//user/开头HttpServletResponse response = ServletActionContext.getResponse();response.setCharacterEncoding("text/html;charset=UTF-8");response.setCharacterEncoding("UTF-8");response.getWriter().print(headImg);}} catch (Exception e) {e.printStackTrace();}}
File及setter,getter

//头像private File headImg;private String headImgFileName;private String headImgContentType;
最终效果:






0 0
原创粉丝点击