参考原文:

Take a Photo from Android Camera and Upload it to a Remote PHP Server

使用Java上传文件

从Apache Software Foundation下载HttpClient 4.3.4。

在工程中添加下面的jar包:

参考sample,写一个简单的上传:

publicstaticvoidmain(String[]args)throwsException{//TODOAuto-generatedmethodstubCloseableHttpClienthttpclient=HttpClients.createDefault();try{HttpPosthttppost=newHttpPost("http://localhost:8003/savetofile.php");//yourserverFileBodybin=newFileBody(newFile("my.jpg"));//imageforuploadingHttpEntityreqEntity=MultipartEntityBuilder.create().addPart("myFile",bin).build();httppost.setEntity(reqEntity);System.out.println("executingrequest"+httppost.getRequestLine());CloseableHttpResponseresponse=httpclient.execute(httppost);try{System.out.println("----------------------------------------");System.out.println(response.getStatusLine());HttpEntityresEntity=response.getEntity();if(resEntity!=null){System.out.println("Responsecontentlength:"+resEntity.getContentLength());}EntityUtils.consume(resEntity);}finally{response.close();}}finally{httpclient.close();}}

Android上拍照

Camera的使用很简单,只需要参考开发者网站的这篇Taking Photos Simply。

调用系统camera只需要如下代码:

Intentintent=newIntent("android.media.action.IMAGE_CAPTURE");startActivityForResult(intent,0);

拍照之后,camera会返回缩略图:

protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){if(requestCode==0&&resultCode==RESULT_OK){Bundleextras=data.getExtras();BitmapimageBitmap=(Bitmap)extras.get("data");mImageView.setImageBitmap(imageBitmap);}}

如果要获得高质量的图,就需要指定照片的保存路径。在AndroidManifest.xml中添加下面的权限:

<uses-permissionandroid:name="android.permission.READ_EXTERNAL_STORAGE"/><uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

修改调用方法:

Intentintent=newIntent("android.media.action.IMAGE_CAPTURE");Intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));startActivityForResult(intent,0);

拍照之后,使用预设的图片路径解码,就可以获取高质量的图:

protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){if(requestCode==0&&resultCode==Activity.RESULT_OK){setPic();}}privatevoidsetPic(){//GetthedimensionsoftheViewinttargetW=mImageView.getWidth();inttargetH=mImageView.getHeight();//GetthedimensionsofthebitmapBitmapFactory.OptionsbmOptions=newBitmapFactory.Options();bmOptions.inJustDecodeBounds=true;BitmapFactory.decodeFile(mCurrentPhotoPath,bmOptions);intphotoW=bmOptions.outWidth;intphotoH=bmOptions.outHeight;//DeterminehowmuchtoscaledowntheimageintscaleFactor=Math.min(photoW/targetW,photoH/targetH);//DecodetheimagefileintoaBitmapsizedtofilltheViewbmOptions.inJustDecodeBounds=false;bmOptions.inSampleSize=scaleFactor;bmOptions.inPurgeable=true;Bitmapbitmap=BitmapFactory.decodeFile(mCurrentPhotoPath,bmOptions);mImageView.setImageBitmap(bitmap);}

从Android客户端传送图片到PHP服务器

要访问Internet,在AndroidManifest.xml中添加访问权限:

<uses-permissionandroid:name="android.permission.INTERNET"/>

参考http://blog.rafaelsanches.com/2011/01/29/upload-using-multipart-post-using-httpclient-in-android/,创建一个类MultipartEntity:

publicclassMultipartEntityimplementsHttpEntity{privateStringboundary=null;ByteArrayOutputStreamout=newByteArrayOutputStream();booleanisSetLast=false;booleanisSetFirst=false;publicMultipartEntity(){this.boundary=System.currentTimeMillis()+"";}publicvoidwriteFirstBoundaryIfNeeds(){if(!isSetFirst){try{out.write(("--"+boundary+"\r\n").getBytes());}catch(finalIOExceptione){}}isSetFirst=true;}publicvoidwriteLastBoundaryIfNeeds(){if(isSetLast){return;}try{out.write(("\r\n--"+boundary+"--\r\n").getBytes());}catch(finalIOExceptione){}isSetLast=true;}publicvoidaddPart(finalStringkey,finalStringvalue){writeFirstBoundaryIfNeeds();try{out.write(("Content-Disposition:form-data;name=\""+key+"\"\r\n").getBytes());out.write("Content-Type:text/plain;charset=UTF-8\r\n".getBytes());out.write("Content-Transfer-Encoding:8bit\r\n\r\n".getBytes());out.write(value.getBytes());out.write(("\r\n--"+boundary+"\r\n").getBytes());}catch(finalIOExceptione){}}publicvoidaddPart(finalStringkey,finalStringfileName,finalInputStreamfin){addPart(key,fileName,fin,"application/octet-stream");}publicvoidaddPart(finalStringkey,finalStringfileName,finalInputStreamfin,Stringtype){writeFirstBoundaryIfNeeds();try{type="Content-Type:"+type+"\r\n";out.write(("Content-Disposition:form-data;name=\""+key+"\";filename=\""+fileName+"\"\r\n").getBytes());out.write(type.getBytes());out.write("Content-Transfer-Encoding:binary\r\n\r\n".getBytes());finalbyte[]tmp=newbyte[4096];intl=0;while((l=fin.read(tmp))!=-1){out.write(tmp,0,l);}out.flush();}catch(finalIOExceptione){}finally{try{fin.close();}catch(finalIOExceptione){}}}publicvoidaddPart(finalStringkey,finalFilevalue){try{addPart(key,value.getName(),newFileInputStream(value));}catch(finalFileNotFoundExceptione){}}@OverridepubliclonggetContentLength(){writeLastBoundaryIfNeeds();returnout.toByteArray().length;}@OverridepublicHeadergetContentType(){returnnewBasicHeader("Content-Type","multipart/form-data;boundary="+boundary);}@OverridepublicbooleanisChunked(){returnfalse;}@OverridepublicbooleanisRepeatable(){returnfalse;}@OverridepublicbooleanisStreaming(){returnfalse;}@OverridepublicvoidwriteTo(finalOutputStreamoutstream)throwsIOException{outstream.write(out.toByteArray());}@OverridepublicHeadergetContentEncoding(){returnnull;}@OverridepublicvoidconsumeContent()throwsIOException,UnsupportedOperationException{if(isStreaming()){thrownewUnsupportedOperationException("Streamingentitydoesnotimplement#consumeContent()");}}@OverridepublicInputStreamgetContent()throwsIOException,UnsupportedOperationException{returnnewByteArrayInputStream(out.toByteArray());}}

使用AsyncTask来完成上传:

privateclassUploadTaskextendsAsyncTask<Bitmap,Void,Void>{protectedVoiddoInBackground(Bitmap...bitmaps){if(bitmaps[0]==null)returnnull;Bitmapbitmap=bitmaps[0];ByteArrayOutputStreamstream=newByteArrayOutputStream();bitmap.compress(Bitmap.CompressFormat.PNG,100,stream);//convertBitmaptoByteArrayOutputStreamInputStreamin=newByteArrayInputStream(stream.toByteArray());//convertByteArrayOutputStreamtoByteArrayInputStreamDefaultHttpClienthttpclient=newDefaultHttpClient();try{HttpPosthttppost=newHttpPost("http://192.168.8.84:8003/savetofile.php");//serverMultipartEntityreqEntity=newMultipartEntity();reqEntity.addPart("myFile",System.currentTimeMillis()+".jpg",in);httppost.setEntity(reqEntity);Log.i(TAG,"request"+httppost.getRequestLine());HttpResponseresponse=null;try{response=httpclient.execute(httppost);}catch(ClientProtocolExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}try{if(response!=null)Log.i(TAG,"response"+response.getStatusLine().toString());}finally{}}finally{}if(in!=null){try{in.close();}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}if(stream!=null){try{stream.close();}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}returnnull;}@OverrideprotectedvoidonPostExecute(Voidresult){//TODOAuto-generatedmethodstubsuper.onPostExecute(result);Toast.makeText(MainActivity.this,R.string.uploaded,Toast.LENGTH_LONG).show();}}

代码

https://github.com/DynamsoftRD/JavaHTTPUpload

Gitclonehttps://github.com/DynamsoftRD/JavaHTTPUpload.git


更多相关文章

  1. Android管理联系人(包含添加,查询,修改和删除;以及不同版本区别)
  2. 在NDK中使用STL
  3. Android中利用OnTouchListener在ImageView中框选显示图片
  4. Cocos2d-x的Android配置以及相关参考文档
  5. Android(安卓)SDK Manager 无法更新SDK
  6. ubuntu右键添加打开终端的快捷菜单
  7. Android(安卓)studio gradle 依赖后报错后出现Failed to resolve
  8. Android(安卓)studio Robotium环境搭建-实测
  9. Android(安卓)Studio添加so库

随机推荐

  1. Android软键盘样式的控制
  2. android Exchange帐户设置
  3. GLES2.0 on Android(安卓)emulator
  4. Android Studio上安装Opencv并配置环境
  5. android 7.0安装apk失败
  6. Android安全风险检测项
  7. android studio 导入 融云问题之一 兼容4
  8. Android view滑动悬浮固定效果实现-踩坑
  9. Android UI 设计规范—— px 转 dp
  10. import android.app.Activity; 失败