Android应用中拍照后获取照片路径并上传的实例分享

Android应用中拍照后获取照片路径并上传的实例分享,第1张

概述Activity中的代码,我只贴出重要的事件部分代码publicvoiddoPhoto(Viewview){destoryBimap();

Activity 中的代码,我只贴出重要的事件部分代码

public voID doPhoto(VIEw vIEw) {   destoryBimap();   String state = Environment.getExternalStorageState();   if (state.equals(Environment.MEDIA_MOUNTED)) {     Intent intent = new Intent("androID.media.action.IMAGE_CAPTURE");     startActivityForResult(intent,1);   } else {     Toast.makeText(MainActivity.this,"没有SD卡",Toast.LENGTH_LONG).show();   } }  @OverrIDe protected voID onActivityResult(int requestCode,int resultCode,Intent data) {   Uri uri = data.getData();   if (uri != null) {     this.photo = BitmapFactory.decodefile(uri.getPath());   }   if (this.photo == null) {     Bundle bundle = data.getExtras();     if (bundle != null) {       this.photo = (Bitmap) bundle.get("data");     } else {       Toast.makeText(MainActivity.this,"拍照失败",Toast.LENGTH_LONG).show();       return;     }   }    fileOutputStream fileOutputStream = null;   try {     // 获取 SD 卡根目录     String saveDir = Environment.getExternalStorageDirectory() + "/meitian_photos";     // 新建目录     file dir = new file(saveDir);     if (! dir.exists()) dir.mkdir();     // 生成文件名     SimpleDateFormat t = new SimpleDateFormat("yyyyMMddssSSS");     String filename = "MT" + (t.format(new Date())) + ".jpg";     // 新建文件     file file = new file(saveDir,filename);     // 打开文件输出流     fileOutputStream = new fileOutputStream(file);     // 生成图片文件     this.photo.compress(Bitmap.CompressFormat.JPEG,100,fileOutputStream);     // 相片的完整路径     this.picPath = file.getPath();     ImageVIEw imageVIEw = (ImageVIEw) findVIEwByID(R.ID.showPhoto);     imageVIEw.setimageBitmap(this.photo);   } catch (Exception e) {     e.printstacktrace();   } finally {     if (fileOutputStream != null) {       try {         fileOutputStream.close();       } catch (Exception e) {         e.printstacktrace();       }     }   } }  /**  * 销毁图片文件  */ private voID destoryBimap() {   if (photo != null && ! photo.isRecycled()) {     photo.recycle();     photo = null;   } } 

Layout 布局页面

<linearLayout xmlns: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 发送http GET POST 请求以及通过 multipartentityBuilder 上传文件

全部使用新的方式 multipartentityBuilder 来处理了。
httpmime-4.3.2.jar   
httpcore-4.3.1.jar  

下载地址:http://hc.apache.org/downloads.cgi
有些镜像貌似打不开,页面上可以可以选择国内的 .cn 后缀的域名镜像服务器来下载

直接上代码了:
ZhttpRequset.java

package com.ai9475.util;  import org.apache.http.httpentity; import org.apache.http.httpResponse; import org.apache.http.httpStatus; import org.apache.http.clIEnt.httpClIEnt; import org.apache.http.clIEnt.methods.httpGet; import org.apache.http.clIEnt.methods.httpPost; import org.apache.http.clIEnt.methods.httpRequestBase; import org.apache.http.entity.mime.httpMultipartMode; import org.apache.http.entity.mime.multipartentityBuilder; import org.apache.http.impl.clIEnt.DefaulthttpClIEnt; import org.apache.http.params.BasichttpParams; import org.apache.http.params.httpconnectionParams; import org.apache.http.params.httpParams; import org.apache.http.protocol.http;  import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.inputStream; import java.nio.charset.Charset;  /**  * Created by ZHOUZ on 14-2-3.  */ public class ZhttpRequest {   public final String http_GET = "GET";    public final String http_POST = "POST";    /**    * 当前请求的 URL    */   protected String url = "";    /**    * http 请求的类型    */   protected String requsetType = http_GET;    /**    * 连接请求的超时时间    */   protected int connectionTimeout = 5000;    /**    * 读取远程数据的超时时间    */   protected int soTimeout = 10000;    /**    * 服务端返回的状态码    */   protected int statusCode = -1;    /**    * 当前链接的字符编码    */   protected String charset = http.UTF_8;    /**    * http GET 请求管理器    */   protected httpRequestBase httpRequest= null;    /**    * http 请求的配置参数    */   protected httpParams httpParameters= null;    /**    * http 请求响应    */   protected httpResponse httpResponse= null;    /**    * http 客户端连接管理器    */   protected httpClIEnt httpClIEnt= null;    /**    * http POST 方式发送多段数据管理器    */   protected multipartentityBuilder multipartentityBuilder= null;    /**    * 绑定 http 请求的事件监听器    */   protected OnhttpRequestListener onhttpRequestListener = null;    public ZhttpRequest(){}    public ZhttpRequest(OnhttpRequestListener Listener) {     this.setonhttpRequestListener(Listener);   }    /**    * 设置当前请求的链接    *    * @param url    * @return    */   public ZhttpRequest setUrl(String url)   {     this.url = url;     return this;   }    /**    * 设置连接超时时间    *    * @param timeout 单位(毫秒),默认 5000    * @return    */   public ZhttpRequest setConnectionTimeout(int timeout)   {     this.connectionTimeout = timeout;     return this;   }    /**    * 设置 socket 读取超时时间    *    * @param timeout 单位(毫秒),默认 10000    * @return    */   public ZhttpRequest setSoTimeout(int timeout)   {     this.soTimeout = timeout;     return this;   }    /**    * 设置获取内容的编码格式    *    * @param charset 默认为 UTF-8    * @return    */   public ZhttpRequest setCharset(String charset)   {     this.charset = charset;     return this;   }    /**    * 获取当前 http 请求的类型    *    * @return    */   public String getRequestType()   {     return this.requsetType;   }    /**    * 判断当前是否 http GET 请求    *    * @return    */   public boolean isGet()   {     return this.requsetType == http_GET;   }    /**    * 判断当前是否 http POST 请求    *    * @return    */   public boolean isPost()   {     return this.requsetType == http_POST;   }    /**    * 获取 http 请求响应信息    *    * @return    */   public httpResponse gethttpResponse()   {     return this.httpResponse;   }    /**    * 获取 http 客户端连接管理器    *    * @return    */   public httpClIEnt gethttpClIEnt()   {     return this.httpClIEnt;   }    /**    * 添加一条 http 请求的 header 信息    *    * @param name    * @param value    * @return    */   public ZhttpRequest addheader(String name,String value)   {     this.httpRequest.addheader(name,value);     return this;   }    /**    * 获取 http GET 控制器    *    * @return    */   public httpGet gethttpGet()   {     return (httpGet) this.httpRequest;   }    /**    * 获取 http POST 控制器    *    * @return    */   public httpPost gethttpPost()   {     return (httpPost) this.httpRequest;   }    /**    * 获取请求的状态码    *    * @return    */   public int getStatusCode()   {     return this.statusCode;   }    /**    * 通过 GET 方式请求数据    *    * @param url    * @return    * @throws IOException    */   public String get(String url) throws Exception   {     this.requsetType = http_GET;     // 设置当前请求的链接     this.setUrl(url);     // 新建 http GET 请求     this.httpRequest = new httpGet(this.url);     // 执行客户端请求     this.httpClIEntExecute();     // 监听服务端响应事件并返回服务端内容     return this.checkStatus();   }    /**    * 获取 http POST 多段数据提交管理器    *    * @return    */   public multipartentityBuilder getmultipartentityBuilder()   {     if (this.multipartentityBuilder == null) {       this.multipartentityBuilder = multipartentityBuilder.create();       // 设置为浏览器兼容模式       multipartentityBuilder.setMode(httpMultipartMode.broWSER_COMPATIBLE);       // 设置请求的编码格式       multipartentityBuilder.setCharset(Charset.forname(this.charset));     }     return this.multipartentityBuilder;   }    /**    * 配置完要 POST 提交的数据后,执行该方法生成数据实体等待发送    */   public voID buildPostEntity()   {     // 生成 http POST 实体     httpentity httpentity = this.multipartentityBuilder.build();     this.gethttpPost().setEntity(httpentity);   }    /**    * 发送 POST 请求    *    * @param url    * @return    * @throws Exception    */   public String post(String url) throws Exception   {     this.requsetType = http_POST;     // 设置当前请求的链接     this.setUrl(url);     // 新建 http POST 请求     this.httpRequest = new httpPost(this.url);     // 执行客户端请求     this.httpClIEntExecute();     // 监听服务端响应事件并返回服务端内容     return this.checkStatus();   }    /**    * 执行 http 请求    *    * @throws Exception    */   protected voID httpClIEntExecute() throws Exception   {     // 配置 http 请求参数     this.httpParameters = new BasichttpParams();     this.httpParameters.setParameter("charset",this.charset);     // 设置 连接请求超时时间     httpconnectionParams.setConnectionTimeout(this.httpParameters,this.connectionTimeout);     // 设置 socket 读取超时时间     httpconnectionParams.setSoTimeout(this.httpParameters,this.soTimeout);     // 开启一个客户端 http 请求     this.httpClIEnt = new DefaulthttpClIEnt(this.httpParameters);     // 启动 http POST 请求执行前的事件监听回调 *** 作(如: 自定义提交的数据字段或上传的文件等)     this.getonhttpRequestListener().onRequest(this);     // 发送 http 请求并获取服务端响应状态     this.httpResponse = this.httpClIEnt.execute(this.httpRequest);     // 获取请求返回的状态码     this.statusCode = this.httpResponse.getStatusline().getStatusCode();   }    /**    * 读取服务端返回的输入流并转换成字符串返回    *    * @throws Exception    */   public String getinputStream() throws Exception   {     // 接收远程输入流     inputStream inStream = this.httpResponse.getEntity().getContent();     // 分段读取输入流数据     ByteArrayOutputStream baos = new ByteArrayOutputStream();     byte[] buf = new byte[1024];     int len = -1;     while ((len = inStream.read(buf)) != -1) {       baos.write(buf,len);     }     // 数据接收完毕退出     inStream.close();     // 将数据转换为字符串保存     return new String(baos.toByteArray(),this.charset);   }    /**    * 关闭连接管理器释放资源    */   protected voID shutdownhttpClIEnt()   {     if (this.httpClIEnt != null && this.httpClIEnt.getConnectionManager() != null) {       this.httpClIEnt.getConnectionManager().shutdown();     }   }    /**    * 监听服务端响应事件并返回服务端内容    *    * @return    * @throws Exception    */   protected String checkStatus() throws Exception   {     OnhttpRequestListener Listener = this.getonhttpRequestListener();     String content;     if (this.statusCode == httpStatus.SC_OK) {       // 请求成功,回调监听事件       content = Listener.onSucceed(this.statusCode,this);     } else {       // 请求失败或其他,回调监听事件       content = Listener.onFailed(this.statusCode,this);     }     // 关闭连接管理器释放资源     this.shutdownhttpClIEnt();     return content;   }    /**    * http 请求 *** 作时的事件监听接口    */   public interface OnhttpRequestListener   {     /**      * 初始化 http GET 或 POST 请求之前的 header 信息配置 或 其他数据配置等 *** 作      *      * @param request      * @throws Exception      */     public voID onRequest(ZhttpRequest request) throws Exception;      /**      * 当 http 请求响应成功时的回调方法      *      * @param statusCode 当前状态码      * @param request      * @return 返回请求获得的字符串内容      * @throws Exception      */     public String onSucceed(int statusCode,ZhttpRequest request) throws Exception;      /**      * 当 http 请求响应失败时的回调方法      *      * @param statusCode 当前状态码      * @param request      * @return 返回请求失败的提示内容      * @throws Exception      */     public String onFailed(int statusCode,ZhttpRequest request) throws Exception;   }    /**    * 绑定 http 请求的监听事件    *    * @param Listener    * @return    */   public ZhttpRequest setonhttpRequestListener(OnhttpRequestListener Listener)   {     this.onhttpRequestListener = Listener;     return this;   }    /**    * 获取已绑定过的 http 请求监听事件    *    * @return    */   public OnhttpRequestListener getonhttpRequestListener()   {     return this.onhttpRequestListener;   } } 

在 Activity 中的使用方法(这里我还是只写主体部分代码):
MainActivity.java

public voID doClick(VIEw vIEw) {   ZhttpRequest get = new ZhttpRequest();   get       .setCharset(http.UTF_8)       .setConnectionTimeout(5000)       .setSoTimeout(5000);   get.setonhttpRequestListener(new ZhttpRequest.OnhttpRequestListener() {     @OverrIDe     public voID onRequest(ZhttpRequest request) throws Exception {      }      @OverrIDe     public String onSucceed(int statusCode,ZhttpRequest request) throws Exception {       return request.getinputStream();     }      @OverrIDe     public String onFailed(int statusCode,ZhttpRequest request) throws Exception {       return "GET 请求失败:statusCode "+ statusCode;     }   });    ZhttpRequest post = new ZhttpRequest();   post       .setCharset(http.UTF_8)       .setConnectionTimeout(5000)       .setSoTimeout(10000);   post.setonhttpRequestListener(new ZhttpRequest.OnhttpRequestListener() {     private String CHARSET = http.UTF_8;     private ContentType TEXT_PLAIN = ContentType.create("text/plain",Charset.forname(CHARSET));      @OverrIDe     public voID onRequest(ZhttpRequest request) throws Exception {       // 设置发送请求的 header 信息       request.addheader("cookie","abc=123;456=爱就是幸福;");       // 配置要 POST 的数据       multipartentityBuilder builder = 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",new file(picPath));       }       request.buildPostEntity();     }      @OverrIDe     public String onSucceed(int statusCode,ZhttpRequest request) throws Exception {       return "POST 请求失败:statusCode "+ statusCode;     }   });    TextVIEw textVIEw = (TextVIEw) findVIEwByID(R.ID.showContent);   String content = "初始内容";   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 (IOException e) {     content = "IO异常:" + e.getMessage();   } catch (Exception e) {     content = "异常:" + e.getMessage();   }   textVIEw.setText(content); } 

其中 picPath 为 SD 卡中的图片路径 String 类型,我是直接拍照后进行上传用的
布局页面
activity_main.xml

<linearLayout xmlns: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); 

总结

以上是内存溢出为你收集整理的Android应用中拍照后获取照片路径并上传的实例分享全部内容,希望文章能够帮你解决Android应用中拍照后获取照片路径并上传的实例分享所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1149513.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存