日期:2014-05-16  浏览次数:20739 次

ajax上传-
js代码
<script type="text/javascript" src="./js/ajaxfileupload.js" charset="UTF-8"></script>
<script language="javascript">
      function ajaxFileUpload() {
   
      $.ajaxFileUpload({
      url : 'useruploadHeadImg',
      secureuri : false,
      fileElementId : 'upFile',
      dataType : 'json',
            success: function (data, status)
          {
               data=data.trim(); //必须加,得到的值前面有一个空隔,需要去掉
               var src="uploadHeadImg/"+data;
               $("#myHeadImg").attr("src",""+src);
          },
          error: function (data, status, e)
          {
           // alert('错误返回!!!!');
          }
      });
      }
</script>

html关键代码

<div>上传
   <input type="file" onchange="ajaxFileUpload()" class="upFile" name="upFile" id="upFile">
</div>
                  
                   <div>图片显示
                       <img  src="uploadHeadImg/<s:property value="#attr.loginUser.headImg"/>"  width="200"  id="myHeadImg"/>
                   </div>

action代码
public String uploadHeadImg() {
SimpleDateFormat simp= new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
String sj=simp.format(new Date());

String  name="img"+sj+".jpg";

String path=ServletActionContext.getServletContext().getRealPath("/");

System.out.println("上传的位置:"+path+"uploadHeadImg"+"\\"+name);
File file=new File(path+"uploadHeadImg\\"+name);  //上传的去处
String data=null;
try {
FileUtils.copyFile(upFile,file);
data=name;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("文件名:"+data);
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("utf-8");
PrintWriter out=null;
try {
out = response.getWriter();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

out.print(data);
out.flush();
System.out.println("出了上传"+data);

return null;
}

//由于ajaxfileupload.js是半成品,存在很多兼容问题,这个ajaxfileupload.js修改后,可支持chrom,360,搜狐,但不支持ie8等系列。