使用ajaxFileUpload插件实现图片无刷新上传

1,在页面

    

<script type="text/javascript" src="js/jquery/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="js/jquery/ajaxfileupload.js"></script>

<script type="text/javascript">
   function uploadimg(obj,id){
    $.ajaxFileUpload({
        url:'uploadImg.do',        secureuri:false,                       //是否启用安全提交,默认为false
        fileElementId:'file'+id,           //文件选择框的id属性
        dataType:'text',          //服务器返回的格式,可以是json或xml等
        success:function(data,status){        //服务器响应成功时的处理函数
        	data = data.replace("<PRE>", '');  //ajaxFileUpload会对服务器响应回来的text内容加上<pre>text</pre>前后缀
            data = data.replace("</PRE>", '');
            data = data.replace("<pre>", '');
            data = data.replace("</pre>", ''); 
        	if(data.substring(0, 1) == 1){	        		
        		$("#img"+id).attr("src",data.substring(2));
        	}
        },
        error:function(data, status, e){ 
        	console.log("上传失败!");
        }
    });
  //file控件只能激发一次,要重新加载
  var nf = obj.cloneNode(true);
  nf.value='';
  obj.parentNode.replaceChild(nf, obj);
}
</script>

<input type="file" id="file1" class="file" name="myfile" onchange="uploadimg(this,1)"/>

 2,后台Controller

  

@RequestMapping(value="/uploadImg",produces="text/plain;charset=UTF-8")
		@ResponseBody
		public String uploadImg(MultipartFile myfile, HttpServletRequest request) throws IOException{
	        System.out.println("文件开始上传开始");
	        String realPath = request.getSession().getServletContext().getRealPath("/upload");
	        String originalFilename = null;
            if(myfile.isEmpty()){
            	System.out.println("上传失败!");
                return "0^上传失败,上传文件为空";
            }else{
            	if("image/jpeg".equals(myfile.getContentType())){
            		originalFilename = myfile.getOriginalFilename();
                    try {
                        FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, originalFilename));
                    } catch (IOException e) {
                    	System.out.println("上传失败!");
                        e.printStackTrace();
                    	return "0^上传失败,文件保存失败";
                    }
            	}else{
            		System.out.println("上传失败!");
	                	return "0^上传失败,文件不是指定的类型";
            	}
            }
	        //因为在Windows下<img src="file:///D:/aa.jpg">能被firefox显示,而<img src="D:/aa.jpg">firefox是不认的
	       System.out.println("上传成功!");
	       System.out.println(originalFilename);
	       return "1^"+request.getContextPath() + "/upload/" + originalFilename;
		}

 附件中有我用的ajaxfileupload.js

本来我是想要json来着,但弄了好长时间没成功,就选text吧!!!

相关推荐