android上传图片到服务器,求服务器那边和android的Activity的完整代码。

服务器端servlet代码:
public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

   //获取输入流,是HTTP协议中的实体内容
    ServletInputStream  sis=request.getInputStream();
   
     File file = new File(request.getSession().getServletContext().getRealPath("/img/"),"img_"+0+".jpg");
     for (int imgnum = 0;file.exists();imgnum++)
     {
      file  = new File(request.getSession().getServletContext().getRealPath("/img/"),"img_"+imgnum+".jpg");
     }
          //缓冲区
          byte buffer[]=new byte[1024];
          FileOutputStream fos=new FileOutputStream(file);
          int len=sis.read(buffer, 0, 1024);
          //把流里的信息循环读入到文件中
          while( len!=-1 )
          {
              fos.write(buffer, 0, len);
              len=sis.readLine(buffer, 0, 1024);
          }
          fos.close();
          sis.close();
}


android客户端代码:
public static void uploadFile(String imageFilePath)
    {
      String actionUrl = "http://192.168.1.32:8080/UploadServer/ImageServlet";
      try
      {
        URL url =new URL(actionUrl);
        HttpURLConnection con=(HttpURLConnection)url.openConnection();
      
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);
      
        con.setRequestMethod("POST");
      
      
        DataOutputStream ds =  new DataOutputStream(con.getOutputStream());
        File file = new File(imageFilePath);
      
        FileInputStream fStream = new FileInputStream(file);
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];

        int length = -1;
      
        while((length = fStream.read(buffer)) != -1)
        {
        
          ds.write(buffer, 0, length);
        }

      
        fStream.close();
        ds.flush();
      
      
        InputStream is = con.getInputStream();
        int ch;
        StringBuffer b =new StringBuffer();
        while( ( ch = is.read() ) != -1 )
        {
          b.append( (char)ch );
        }
      
      
        ds.close();
      }
      catch(Exception e)
      {
       e.printStackTrace();
      }
    
    }

你可能感兴趣的:(android,servlet)