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();
      }
    
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值