android 上传Bitmap到服务器端
16lz
2021-01-26
转载于:
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 ?
- //createabitmapvariablebeforeanything;
- privateBitmapbitmap;
- //variabletosetanametotheimageintoSDcard;
- //thisvariable,youhavetoputthepathfortheFile,It'suptoyou;
- publicstaticStringexsistingFileName;
- //sendDataisthefunctionname,tocallit,youcanusesomethinglikesendData(null);
- //remembertowrapitintoatrycatch;
- publicvoidsendData(String[]args)throwsException{
- try{
- HttpClienthttpClient=newDefaultHttpClient();
- HttpContextlocalContext=newBasicHttpContext();
- //here,changeittoyourphp;
- HttpPosthttpPost=newHttpPost("http://www.myURL.com/myPHP.php");
- MultipartEntityentity=newMultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
- bitmap=BitmapFactory.decodeFile(exsistingFileName);
- //youcanchangetheformatofyouimagecompressedforwhatdoyouwant;
- //nowitissetupto640x480;
- BitmapbmpCompressed=Bitmap.createScaledBitmap(bitmap,640,480,true);
- ByteArrayOutputStreambos=newByteArrayOutputStream();
- //CompressFormatsetuptoJPG,youcanchangetoPNGorwhateveryouwant;
- bmpCompressed.compress(CompressFormat.JPEG,100,bos);
- byte[]data=bos.toByteArray();
- //sendingaStringparam;
- entity.addPart("myParam",newStringBody("myvalue"));
- //sendingaImage;
- //notehere,thatyoucansendmorethanoneimage,justaddanotherparam,sameruletotheString;
- entity.addPart("myImage",newByteArrayBody(data,"temp.jpg"));
- httpPost.setEntity(entity);
- HttpResponseresponse=httpClient.execute(httpPost,localContext);
- BufferedReaderreader=newBufferedReader(newInputStreamReader(response.getEntity().getContent(),"UTF-8"));
- StringsResponse=reader.readLine();
- }catch(Exceptione){
- Log.v("myApp","Someerrorcameup");
- }
- }
更多相关文章
- Android(安卓)通用Dialog中设置RecyclerView
- Android——Google应用移植时的包依赖关系
- Android(安卓)一键分享功能简单实现
- android:点击popupwindow以外区域 popupwindow自动消失(转载)
- (转载)Android应用程序签名系统的签名(SignApk.jar)
- android多语言与国际化(记录)
- [转载] android中的surface
- Android源码50例汇总,欢迎各位下载 【转载自51CTO】
- android studio 学习入门篇(转载)