阅读更多

服务器端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();
      }
    
    }

更多相关文章

  1. android中webview开启了硬件加速后会出现闪烁问题
  2. Android(安卓)和 PHP 之间进行数据加密传输
  3. android 源代码研究之----frameworks-----status bar 状态栏
  4. android开发出现No Launcher activity found!解决方案
  5. socket连接
  6. android fragment ,listview 嵌套横向HorizontalScrollView 实现H
  7. Android一键锁屏开发全过程【源码+附图】
  8. Android(安卓)代码实现重启
  9. Android(安卓)Timer 更好方法

随机推荐

  1. Android Studio 开发常用快捷键
  2. Android 应用程序签名
  3. Android 禁止带有home属性的APP安装
  4. android基础之Application
  5. android 设置中文字体。。。。
  6. android 各版本发布时间
  7. Android Studio 更新中的问题
  8. Android设置默认时间
  9. SeekBar自定义样式
  10. Android 一些注意