图片上传
2016-12-01 10:00
344 查看
选择本地图片,并上传到服务器:
布局文件:
转换成Base64:
/* * 图片上传 * */ public class MainActivity extends Activity implements View.OnClickListener { private Button selectImage,uploadImage; private ImageView imageView; private TextView tv_picName,tv_picPath; public static final String requestURL = "http://103.8.220.166:40000/lechu/device/image/fileupload"; public static final String SUCCESS="00000"; public static final String FAILURE="00001"; private String picPath = null; private String picName = null; public String displayMessage,retCode,retInfo; private static final String TAG = "uploadImage"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //选择图片按钮 selectImage = (Button) this.findViewById(R.id.btn_select); //上传按钮 uploadImage = (Button) this.findViewById(R.id.btn_upload); //图片显示 selectImage.setOnClickListener(this); uploadImage.setOnClickListener(this); imageView = (ImageView) this.findViewById(R.id.iv_selected); //String str = BaseStrem.GetImgPath(); //显示图片名称 tv_picName = (TextView)findViewById(R.id.tv_picName); //显示图片路径 tv_picPath = (TextView)findViewById(R.id.tv_picPath); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.btn_select: Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); //回调图片类使用 startActivityForResult(intent,RESULT_CANCELED); break; case R.id.btn_upload: final MyHandler myHandler = new MyHandler(); if(picPath!=null && picPath.length()>0){ //对网络的访问要在单独的线程中操作,并利用handler在线程间传递数据 new Thread(){ public void run(){ Looper.prepare(); //displayMessage是一个的字符串,{"retCode":"00000","retInfo":"操作成功","retResult":""} FileUtil fileUtil = new FileUtil(); displayMessage = fileUtil.uploadFilePost(picPath,getLocalMac(),requestURL); //displayMessage = upLoadFile(picName,picPath,requestURL); try{ JSONObject jsonObject1 = new JSONObject(displayMessage); retCode = jsonObject1.get("retCode").toString(); retInfo = jsonObject1.get("retInfo").toString(); }catch (Exception ex){ ex.printStackTrace(); } Bundle bundle = new Bundle(); bundle.putString("retCode",retCode); bundle.putString("retInfo",retInfo); Message msg = new Message(); msg.setData(bundle); myHandler.sendMessage(msg); } }.start(); } break; } } //回传图片信息 protected void onActivityResult(int requestCode,int resultCode,Intent data){ super.onActivityResult(requestCode, resultCode, data); if(resultCode == Activity.RESULT_OK){ Uri uri = data.getData(); Log.e(TAG,"uri="+uri); try{ String[] pojo = {MediaStore.Images.Media.DATA}; Cursor cursor = managedQuery(uri,pojo,null,null,null); if(cursor!=null){ ContentResolver cr = this.getContentResolver(); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); String path = cursor.getString(column_index); //获取图片名称 String[] name = path.split("/"); picName = name[name.length-1]; tv_picName.setText(picName+"=="+getLocalMac()); //当图片为jpg或png格式时显示图片 if(path.endsWith("jpg")||path.endsWith("png")){ picPath = path; Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri)); imageView.setImageBitmap(bitmap); Log.i("pictruedetail",picPath+"==="+picName); tv_picPath.setText(picPath); }else{ alert(); } } }catch (Exception ex){ ex.printStackTrace(); } } } private void alert() { Dialog dialog = new AlertDialog.Builder(this) .setTitle("提示") .setMessage("您选择的不是有效的图片") .setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { picPath = null; } }) .create(); dialog.show(); } //获取设备的MAC地址 public String getLocalMac(){ WifiManager wifiManager = (WifiManager)getSystemService(WIFI_SERVICE); WifiInfo info = wifiManager.getConnectionInfo(); return info.getMacAddress(); } class MyHandler extends Handler{ public MyHandler(){ } public MyHandler(Looper looper){ super(looper); } public void handleMessage(Message msg) { retCode = msg.getData().getString("retCode"); if(retCode.equals("00000")){ Toast.makeText(MainActivity.this,msg.getData().getString("retInfo"),Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(MainActivity.this,"操作失败",Toast.LENGTH_SHORT).show(); } } } //图片上传,参数图片名称,图片路径,请求url public String upLoadFile(String picName1,String picPath1,String requestURL){ String retCode=null; String displayStr = null; JSONObject totalJson = new JSONObject(); JSONArray jsonArray = new JSONArray(); JSONObject jsonObject = new JSONObject(); try{ jsonObject.put("cameraId",1); jsonObject.put("pictureName",picName1); //jsonObject.put("pictureData",picPath1); jsonObject.put("pictureData",BaseStrem.GetImgPath(picPath1)); //将JSON对象放到数组中 jsonArray.put(jsonObject); //将数组再封装到总的JSON中 totalJson.put("pictures",jsonArray); //获取MAC地址,并转换成小写不带:的形式 String[] macAddr = getLocalMac().toLowerCase().split(":"); String mac=""; for(int i=0;i<macAddr.length;i++){ mac = mac+macAddr[i]; } totalJson.put("deviceId",mac); Log.i("JSONMAC",mac); }catch (Exception ex){ ex.printStackTrace(); } Log.i("JSON", totalJson.toString()); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(requestURL); try{ StringEntity entity = new StringEntity(totalJson.toString()); post.setEntity(entity); HttpResponse responseStr = client.execute(post); HttpEntity httpEntity = responseStr.getEntity(); displayStr = EntityUtils.toString(httpEntity); Log.i("passStr", displayStr); }catch (Exception ex){ ex.printStackTrace(); } return displayStr; } }
布局文件:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <Button android:id="@+id/btn_select" android:text="选择图片" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:text="上传图片" android:id="@+id/btn_upload" android:layout_below="@+id/btn_select" android:layout_width="match_parent" android:layout_height="wrap_content" /> <ImageView android:id="@+id/iv_selected" android:layout_below="@+id/btn_upload" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/tv_picName" android:layout_below="@+id/iv_selected" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/tv_picPath" android:layout_below="@+id/tv_picName" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout>
转换成Base64:
package com.h.fileinput; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Base64; public class BaseStrem{ //获得Base流的方法 public static String GetImgPath(String imgpath){ Bitmap bitmap=null; String imgstrem=null; bitmap=getDiskBitmap(imgpath); imgstrem=bitmapToBase64(bitmap); return imgstrem; } //传图片地址返回一个BitMap public static Bitmap getDiskBitmap(String pathString) { Bitmap bitmap = null; try { File file = new File(pathString); if(file.exists()) { bitmap = BitmapFactory.decodeFile(pathString); } } catch (Exception e) { // TODO: handle exception } return bitmap; } //传BitMap返回Base64流 public static String bitmapToBase64(Bitmap bitmap) { String result = null; ByteArrayOutputStream baos = null; try { if (bitmap != null) { baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); baos.flush(); baos.close(); byte[] bitmapBytes = baos.toByteArray(); result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (baos != null) { baos.flush(); baos.close(); } } catch (IOException e) { e.printStackTrace(); } } return result; } //传入Base64流返回一个BitMap public static Bitmap stringtoBitmap(String string) { // 将字符串转换成Bitmap类型 Bitmap bitmap = null; try { byte[] bitmapArray; bitmapArray = Base64.decode(string, Base64.DEFAULT); bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length); } catch (Exception e) { e.printStackTrace(); } return bitmap; } }
相关文章推荐
- 上传时图片可以改大小,图上写字
- 关于图片上传方案选择的依据
- 求助:怎样上传图片呀?
- 不改安全级别,上传前,在客户端判断图片文件大小
- 上传预览图片
- 用ASP.NET上传图片并生成带版权信息的缩略图
- 无组件上传图片到数据库中
- 在ASP.NET中上传图片并生成缩略图的C#源码
- 操作Oracle数据库实现上传图片到Blob类型的字段出现的问题
- 无组件上传图片到数据库中,最完整解决方案
- asp.net上传图片并同时生成缩略图
- dudu: 能否给图片上传加分页功能
- 图片上传的例子
- 为freetextbox1.6.5上传图片加上水印
- 单个图片上传到数据库
- asp.net上传文件图片的做法
- 让FreeTextBox(一个HTML编辑器) 支持上传本地图片并插入编辑器中
- 建议DuDu:实现上传图片能够以目录方式存放.
- 把图片上传到数据库
- BBS 设计思路系列 ---- 上传、下载文件、图片