Android应用中拍照后获取照片路径并上传的实例分享
Activity中的代码,我只贴出重要的事件部分代码
publicvoiddoPhoto(Viewview) { destoryBimap(); Stringstate=Environment.getExternalStorageState(); if(state.equals(Environment.MEDIA_MOUNTED)){ Intentintent=newIntent("android.media.action.IMAGE_CAPTURE"); startActivityForResult(intent,1); }else{ Toast.makeText(MainActivity.this,"没有SD卡",Toast.LENGTH_LONG).show(); } } @Override protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata) { Uriuri=data.getData(); if(uri!=null){ this.photo=BitmapFactory.decodeFile(uri.getPath()); } if(this.photo==null){ Bundlebundle=data.getExtras(); if(bundle!=null){ this.photo=(Bitmap)bundle.get("data"); }else{ Toast.makeText(MainActivity.this,"拍照失败",Toast.LENGTH_LONG).show(); return; } } FileOutputStreamfileOutputStream=null; try{ //获取SD卡根目录 StringsaveDir=Environment.getExternalStorageDirectory()+"/meitian_photos"; //新建目录 Filedir=newFile(saveDir); if(!dir.exists())dir.mkdir(); //生成文件名 SimpleDateFormatt=newSimpleDateFormat("yyyyMMddssSSS"); Stringfilename="MT"+(t.format(newDate()))+".jpg"; //新建文件 Filefile=newFile(saveDir,filename); //打开文件输出流 fileOutputStream=newFileOutputStream(file); //生成图片文件 this.photo.compress(Bitmap.CompressFormat.JPEG,100,fileOutputStream); //相片的完整路径 this.picPath=file.getPath(); ImageViewimageView=(ImageView)findViewById(R.id.showPhoto); imageView.setImageBitmap(this.photo); }catch(Exceptione){ e.printStackTrace(); }finally{ if(fileOutputStream!=null){ try{ fileOutputStream.close(); }catch(Exceptione){ e.printStackTrace(); } } } } /** *销毁图片文件 */ privatevoiddestoryBimap() { if(photo!=null&&!photo.isRecycled()){ photo.recycle(); photo=null; } }
Layout布局页面
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <ScrollView android:layout_width="fill_parent" android:layout_height="fill_parent" > <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/doPhoto" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="10dp" android:layout_marginBottom="10dp" android:text="拍照" android:onClick="doPhoto" /> <TextView android:id="@+id/showContent" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="10dp" /> <ImageView android:id="@+id/showPhoto" android:layout_width="fill_parent" android:layout_height="250dp" android:scaleType="centerCrop" android:src="@drawable/add" android:layout_marginBottom="10dp" /> </LinearLayout> </ScrollView> </LinearLayout>
其中的上传工具类我们下面一起来看:
Android发送HTTPGETPOST请求以及通过MultipartEntityBuilder上传文件
全部使用新的方式MultipartEntityBuilder来处理了。
httpmime-4.3.2.jar
httpcore-4.3.1.jar
下载地址:http://hc.apache.org/downloads.cgi
有些镜像貌似打不开,页面上可以可以选择国内的.cn后缀的域名镜像服务器来下载
直接上代码了:
ZHttpRequset.java
packagecom.ai9475.util; importorg.apache.http.HttpEntity; importorg.apache.http.HttpResponse; importorg.apache.http.HttpStatus; importorg.apache.http.client.HttpClient; importorg.apache.http.client.methods.HttpGet; importorg.apache.http.client.methods.HttpPost; importorg.apache.http.client.methods.HttpRequestBase; importorg.apache.http.entity.mime.HttpMultipartMode; importorg.apache.http.entity.mime.MultipartEntityBuilder; importorg.apache.http.impl.client.DefaultHttpClient; importorg.apache.http.params.BasicHttpParams; importorg.apache.http.params.HttpConnectionParams; importorg.apache.http.params.HttpParams; importorg.apache.http.protocol.HTTP; importjava.io.ByteArrayOutputStream; importjava.io.IOException; importjava.io.InputStream; importjava.nio.charset.Charset; /** *CreatedbyZHOUZon14-2-3. */ publicclassZHttpRequest { publicfinalStringHTTP_GET="GET"; publicfinalStringHTTP_POST="POST"; /** *当前请求的URL */ protectedStringurl=""; /** *HTTP请求的类型 */ protectedStringrequsetType=HTTP_GET; /** *连接请求的超时时间 */ protectedintconnectionTimeout=5000; /** *读取远程数据的超时时间 */ protectedintsoTimeout=10000; /** *服务端返回的状态码 */ protectedintstatusCode=-1; /** *当前链接的字符编码 */ protectedStringcharset=HTTP.UTF_8; /** *HTTPGET请求管理器 */ protectedHttpRequestBasehttpRequest=null; /** *HTTP请求的配置参数 */ protectedHttpParamshttpParameters=null; /** *HTTP请求响应 */ protectedHttpResponsehttpResponse=null; /** *HTTP客户端连接管理器 */ protectedHttpClienthttpClient=null; /** *HTTPPOST方式发送多段数据管理器 */ protectedMultipartEntityBuildermultipartEntityBuilder=null; /** *绑定HTTP请求的事件监听器 */ protectedOnHttpRequestListeneronHttpRequestListener=null; publicZHttpRequest(){} publicZHttpRequest(OnHttpRequestListenerlistener){ this.setOnHttpRequestListener(listener); } /** *设置当前请求的链接 * *@paramurl *@return */ publicZHttpRequestsetUrl(Stringurl) { this.url=url; returnthis; } /** *设置连接超时时间 * *@paramtimeout单位(毫秒),默认5000 *@return */ publicZHttpRequestsetConnectionTimeout(inttimeout) { this.connectionTimeout=timeout; returnthis; } /** *设置socket读取超时时间 * *@paramtimeout单位(毫秒),默认10000 *@return */ publicZHttpRequestsetSoTimeout(inttimeout) { this.soTimeout=timeout; returnthis; } /** *设置获取内容的编码格式 * *@paramcharset默认为UTF-8 *@return */ publicZHttpRequestsetCharset(Stringcharset) { this.charset=charset; returnthis; } /** *获取当前HTTP请求的类型 * *@return */ publicStringgetRequestType() { returnthis.requsetType; } /** *判断当前是否HTTPGET请求 * *@return */ publicbooleanisGet() { returnthis.requsetType==HTTP_GET; } /** *判断当前是否HTTPPOST请求 * *@return */ publicbooleanisPost() { returnthis.requsetType==HTTP_POST; } /** *获取HTTP请求响应信息 * *@return */ publicHttpResponsegetHttpResponse() { returnthis.httpResponse; } /** *获取HTTP客户端连接管理器 * *@return */ publicHttpClientgetHttpClient() { returnthis.httpClient; } /** *添加一条HTTP请求的header信息 * *@paramname *@paramvalue *@return */ publicZHttpRequestaddHeader(Stringname,Stringvalue) { this.httpRequest.addHeader(name,value); returnthis; } /** *获取HTTPGET控制器 * *@return */ publicHttpGetgetHttpGet() { return(HttpGet)this.httpRequest; } /** *获取HTTPPOST控制器 * *@return */ publicHttpPostgetHttpPost() { return(HttpPost)this.httpRequest; } /** *获取请求的状态码 * *@return */ publicintgetStatusCode() { returnthis.statusCode; } /** *通过GET方式请求数据 * *@paramurl *@return *@throwsIOException */ publicStringget(Stringurl)throwsException { this.requsetType=HTTP_GET; //设置当前请求的链接 this.setUrl(url); //新建HTTPGET请求 this.httpRequest=newHttpGet(this.url); //执行客户端请求 this.httpClientExecute(); //监听服务端响应事件并返回服务端内容 returnthis.checkStatus(); } /** *获取HTTPPOST多段数据提交管理器 * *@return */ publicMultipartEntityBuildergetMultipartEntityBuilder() { if(this.multipartEntityBuilder==null){ this.multipartEntityBuilder=MultipartEntityBuilder.create(); //设置为浏览器兼容模式 multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); //设置请求的编码格式 multipartEntityBuilder.setCharset(Charset.forName(this.charset)); } returnthis.multipartEntityBuilder; } /** *配置完要POST提交的数据后,执行该方法生成数据实体等待发送 */ publicvoidbuildPostEntity() { //生成HTTPPOST实体 HttpEntityhttpEntity=this.multipartEntityBuilder.build(); this.getHttpPost().setEntity(httpEntity); } /** *发送POST请求 * *@paramurl *@return *@throwsException */ publicStringpost(Stringurl)throwsException { this.requsetType=HTTP_POST; //设置当前请求的链接 this.setUrl(url); //新建HTTPPOST请求 this.httpRequest=newHttpPost(this.url); //执行客户端请求 this.httpClientExecute(); //监听服务端响应事件并返回服务端内容 returnthis.checkStatus(); } /** *执行HTTP请求 * *@throwsException */ protectedvoidhttpClientExecute()throwsException { //配置HTTP请求参数 this.httpParameters=newBasicHttpParams(); this.httpParameters.setParameter("charset",this.charset); //设置连接请求超时时间 HttpConnectionParams.setConnectionTimeout(this.httpParameters,this.connectionTimeout); //设置socket读取超时时间 HttpConnectionParams.setSoTimeout(this.httpParameters,this.soTimeout); //开启一个客户端HTTP请求 this.httpClient=newDefaultHttpClient(this.httpParameters); //启动HTTPPOST请求执行前的事件监听回调操作(如:自定义提交的数据字段或上传的文件等) this.getOnHttpRequestListener().onRequest(this); //发送HTTP请求并获取服务端响应状态 this.httpResponse=this.httpClient.execute(this.httpRequest); //获取请求返回的状态码 this.statusCode=this.httpResponse.getStatusLine().getStatusCode(); } /** *读取服务端返回的输入流并转换成字符串返回 * *@throwsException */ publicStringgetInputStream()throwsException { //接收远程输入流 InputStreaminStream=this.httpResponse.getEntity().getContent(); //分段读取输入流数据 ByteArrayOutputStreambaos=newByteArrayOutputStream(); byte[]buf=newbyte[1024]; intlen=-1; while((len=inStream.read(buf))!=-1){ baos.write(buf,0,len); } //数据接收完毕退出 inStream.close(); //将数据转换为字符串保存 returnnewString(baos.toByteArray(),this.charset); } /** *关闭连接管理器释放资源 */ protectedvoidshutdownHttpClient() { if(this.httpClient!=null&&this.httpClient.getConnectionManager()!=null){ this.httpClient.getConnectionManager().shutdown(); } } /** *监听服务端响应事件并返回服务端内容 * *@return *@throwsException */ protectedStringcheckStatus()throwsException { OnHttpRequestListenerlistener=this.getOnHttpRequestListener(); Stringcontent; if(this.statusCode==HttpStatus.SC_OK){ //请求成功,回调监听事件 content=listener.onSucceed(this.statusCode,this); }else{ //请求失败或其他,回调监听事件 content=listener.onFailed(this.statusCode,this); } //关闭连接管理器释放资源 this.shutdownHttpClient(); returncontent; } /** *HTTP请求操作时的事件监听接口 */ publicinterfaceOnHttpRequestListener { /** *初始化HTTPGET或POST请求之前的header信息配置或其他数据配置等操作 * *@paramrequest *@throwsException */ publicvoidonRequest(ZHttpRequestrequest)throwsException; /** *当HTTP请求响应成功时的回调方法 * *@paramstatusCode当前状态码 *@paramrequest *@return返回请求获得的字符串内容 *@throwsException */ publicStringonSucceed(intstatusCode,ZHttpRequestrequest)throwsException; /** *当HTTP请求响应失败时的回调方法 * *@paramstatusCode当前状态码 *@paramrequest *@return返回请求失败的提示内容 *@throwsException */ publicStringonFailed(intstatusCode,ZHttpRequestrequest)throwsException; } /** *绑定HTTP请求的监听事件 * *@paramlistener *@return */ publicZHttpRequestsetOnHttpRequestListener(OnHttpRequestListenerlistener) { this.onHttpRequestListener=listener; returnthis; } /** *获取已绑定过的HTTP请求监听事件 * *@return */ publicOnHttpRequestListenergetOnHttpRequestListener() { returnthis.onHttpRequestListener; } }
在Activity中的使用方法(这里我还是只写主体部分代码):
MainActivity.java
publicvoiddoClick(Viewview) { ZHttpRequestget=newZHttpRequest(); get .setCharset(HTTP.UTF_8) .setConnectionTimeout(5000) .setSoTimeout(5000); get.setOnHttpRequestListener(newZHttpRequest.OnHttpRequestListener(){ @Override publicvoidonRequest(ZHttpRequestrequest)throwsException{ } @Override publicStringonSucceed(intstatusCode,ZHttpRequestrequest)throwsException{ returnrequest.getInputStream(); } @Override publicStringonFailed(intstatusCode,ZHttpRequestrequest)throwsException{ return"GET请求失败:statusCode"+statusCode; } }); ZHttpRequestpost=newZHttpRequest(); post .setCharset(HTTP.UTF_8) .setConnectionTimeout(5000) .setSoTimeout(10000); post.setOnHttpRequestListener(newZHttpRequest.OnHttpRequestListener(){ privateStringCHARSET=HTTP.UTF_8; privateContentTypeTEXT_PLAIN=ContentType.create("text/plain",Charset.forName(CHARSET)); @Override publicvoidonRequest(ZHttpRequestrequest)throwsException{ //设置发送请求的header信息 request.addHeader("cookie","abc=123;456=爱就是幸福;"); //配置要POST的数据 MultipartEntityBuilderbuilder=request.getMultipartEntityBuilder(); builder.addTextBody("p1","abc"); builder.addTextBody("p2","中文",TEXT_PLAIN); builder.addTextBody("p3","abc中文cba",TEXT_PLAIN); if(picPath!=null&&!"".equals(picPath)){ builder.addTextBody("pic",picPath); builder.addBinaryBody("file",newFile(picPath)); } request.buildPostEntity(); } @Override publicStringonSucceed(intstatusCode,ZHttpRequestrequest)throwsException{ returnrequest.getInputStream(); } @Override publicStringonFailed(intstatusCode,ZHttpRequestrequest)throwsException{ return"POST请求失败:statusCode"+statusCode; } }); TextViewtextView=(TextView)findViewById(R.id.showContent); Stringcontent="初始内容"; try{ if(view.getId()==R.id.doGet){ content=get.get("http://www.baidu.com"); content="GET数据:isGet:"+(get.isGet()?"yes":"no")+"=>"+content; }else{ content=post.post("http://192.168.1.6/test.php"); content="POST数据:isPost"+(post.isPost()?"yes":"no")+"=>"+content; } }catch(IOExceptione){ content="IO异常:"+e.getMessage(); }catch(Exceptione){ content="异常:"+e.getMessage(); } textView.setText(content); }
其中picPath为SD卡中的图片路径String类型,我是直接拍照后进行上传用的
布局页面
activity_main.xml
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <ScrollView android:layout_width="fill_parent" android:layout_height="fill_parent" > <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/doGet" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="10dp" android:layout_marginBottom="10dp" android:text="GET请求" android:onClick="doClick" /> <Button android:id="@+id/doPost" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="10dp" android:layout_marginBottom="10dp" android:text="POST请求" android:onClick="doClick" /> <Button android:id="@+id/doPhoto" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="10dp" android:layout_marginBottom="10dp" android:text="拍照" android:onClick="doPhoto" /> <TextView android:id="@+id/showContent" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="10dp" /> <ImageView android:id="@+id/showPhoto" android:layout_width="fill_parent" android:layout_height="250dp" android:scaleType="centerCrop" android:src="@drawable/add" android:layout_marginBottom="10dp" /> </LinearLayout> </ScrollView> </LinearLayout>
至于服务端我用的PHP,只是简单的输出获取到的数据而已
<?php echo'GET:<br>'."\n"; //print_r(array_map('urldecode',$_GET)); print_r($_GET); echo'<br>'."\n".'POST:<br>'."\n"; //print_r(array_map('urldecode',$_POST)); print_r($_POST); echo'<br>'."\n".'FILES:<br>'."\n"; print_r($_FILES); echo'<br>'."\n".'COOKIES:<br>'."\n"; print_r($_COOKIE);