转载于:

Last week, I faced a problem to send an image to the server, I have tried a lot of ways, but seemed that nothing would work.

After some research, I found theHTTPClient API, this API helped me to do the dirty work, and it did pretty well. I will show you now, how to upload images and/or strings to the web server.

It’s pretty simple, actually. I gonna do in only one function!

view plain copy to clipboard print ?
  1. //createabitmapvariablebeforeanything;
  2. privateBitmapbitmap;
  3. //variabletosetanametotheimageintoSDcard;
  4. //thisvariable,youhavetoputthepathfortheFile,It'suptoyou;
  5. publicstaticStringexsistingFileName;
  6. //sendDataisthefunctionname,tocallit,youcanusesomethinglikesendData(null);
  7. //remembertowrapitintoatrycatch;
  8. publicvoidsendData(String[]args)throwsException{
  9. try{
  10. HttpClienthttpClient=newDefaultHttpClient();
  11. HttpContextlocalContext=newBasicHttpContext();
  12. //here,changeittoyourphp;
  13. HttpPosthttpPost=newHttpPost("http://www.myURL.com/myPHP.php");
  14. MultipartEntityentity=newMultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
  15. bitmap=BitmapFactory.decodeFile(exsistingFileName);
  16. //youcanchangetheformatofyouimagecompressedforwhatdoyouwant;
  17. //nowitissetupto640x480;
  18. BitmapbmpCompressed=Bitmap.createScaledBitmap(bitmap,640,480,true);
  19. ByteArrayOutputStreambos=newByteArrayOutputStream();
  20. //CompressFormatsetuptoJPG,youcanchangetoPNGorwhateveryouwant;
  21. bmpCompressed.compress(CompressFormat.JPEG,100,bos);
  22. byte[]data=bos.toByteArray();
  23. //sendingaStringparam;
  24. entity.addPart("myParam",newStringBody("myvalue"));
  25. //sendingaImage;
  26. //notehere,thatyoucansendmorethanoneimage,justaddanotherparam,sameruletotheString;
  27. entity.addPart("myImage",newByteArrayBody(data,"temp.jpg"));
  28. httpPost.setEntity(entity);
  29. HttpResponseresponse=httpClient.execute(httpPost,localContext);
  30. BufferedReaderreader=newBufferedReader(newInputStreamReader(response.getEntity().getContent(),"UTF-8"));
  31. StringsResponse=reader.readLine();
  32. }catch(Exceptione){
  33. Log.v("myApp","Someerrorcameup");
  34. }
  35. }

更多相关文章

  1. Android(安卓)通用Dialog中设置RecyclerView
  2. Android——Google应用移植时的包依赖关系
  3. Android(安卓)一键分享功能简单实现
  4. android:点击popupwindow以外区域 popupwindow自动消失(转载)
  5. (转载)Android应用程序签名系统的签名(SignApk.jar)
  6. android多语言与国际化(记录)
  7. [转载] android中的surface
  8. Android源码50例汇总,欢迎各位下载 【转载自51CTO】
  9. android studio 学习入门篇(转载)

随机推荐

  1. android kernel最新下载地址
  2. zz :Android测试之Monkey
  3. Android(安卓)数据存储与IO (二)
  4. Unity和Android交互
  5. Android开发之Shape和Selector、Layer-li
  6. React Native基础之Image
  7. Android的数据存储方式
  8. Android(安卓)完全退出
  9. QT 仿android launcher
  10. 开发android,我们需要哪些技能基础。