ajax验证,上传图片流

jsp

 String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

     <script type="text/javascript">
 var request;
 function createRequest() {
   try {
     request = new XMLHttpRequest();
   } catch (trymicrosoft) {
     try {
       request = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (othermicrosoft) {
       try {
         request = new ActiveXObject("Microsoft.XMLHTTP");
       } catch (failed) {
         request = false;
       }
     }
   }
     if (!request)
      alert("Error initializing XMLHttpRequest!");
   }
        //用以拿到输入框的帐号和密码以及后台Servlet地址
 function uploadImage(imageStream,fileName){
 
  var url = “url”;
  createRequest();
  request.open("post",url,true);
  request.onreadystatechange = processResponse;
  request.send(null);
 }
 
 function MyLogin(){
    document.getElementById("login").style.visibility="visible";
 }
 function processResponse(){
 var res=request.responseText;
      if (request.readyState == 4) { // 判断对象状态
         if (request.status == 200) { // 信息已经成功返回,开始处理信息
              //由后台Servlet传过来的信息
                  document.all['pic'].src = "<%=basePath%>/idCardImage/"+res;
            } else { //页面不正常
             
                window.alert("您所请求的页面有异常。");
            }
        }
   }
 </script>

 

java

上传图片

 public String uploadImage(String filename, String image,String fileDir) { 
     FileOutputStream fos = null; 
     try{ 
         byte[] buffer = new BASE64Decoder().decodeBuffer(image);   //对android传过来的图片字符串进行解码  
         File destDir = new File(fileDir);   
         if(!destDir.exists()) destDir.mkdir(); 
         fos = new FileOutputStream(new File(destDir,filename));   //保存图片 
         fos.write(buffer); 
         fos.flush(); 
         fos.close(); 
         return "true"; 
     }catch (Exception e){ 
         e.printStackTrace(); 
         return "false";
     } 
 }

 

public ActionForward uploadImage(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response) {
  String imageStream = request.getParameter("imageStream");
  String fileName = request.getParameter("fileName");
  fileName = fileName +".jpg";
  imageStream = imageStream.replaceAll(" ", "+");//ajax传入的图片流把加号替换成了空格,需要转一下
  ServletContext context = this.servlet.getServletContext(); // 文件路径
  
  String fileDir = context.getRealPath("/") + "idCardImage/";
  response.setContentType("text/xml; charset=utf-8");  
        PrintWriter out=null;
  try {
   out = response.getWriter();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }  
       
        String flag = uploadImage(fileName,imageStream,fileDir);
        
        if(flag.equals("true")){   
            out.print(fileName);   
            return null;  
        } else {  
          out.print(fileName);    
            return null;  
        }  
 }

你可能感兴趣的:(ajax验证,上传图片流)