android选择图片或拍照图片上传到服务器(包括上传参数)
open failed: EACCES (Permission denied)"权限已加,写入sd卡仍报错的解决办法
权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
界面:
代码:
load_weight_item.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/upload_pic" android:layout_width="match_parent" android:layout_height="290dp" android:layout_gravity="center_horizontal" android:layout_alignParentRight="true" android:layout_below="@+id/receive_weight" android:layout_centerVertical="true" android:layout_marginTop="10dp" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:adjustViewBounds="true"/> <Button android:id="@+id/select_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:layout_marginLeft="30.0dip" android:layout_marginRight="30.0dip" android:layout_gravity="center" android:layout_centerInParent="true" android:scaleType="fitXY" android:background="@mipmap/select_pic_btn" /> <Button android:id="@+id/upload_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:layout_marginLeft="30.0dip" android:layout_marginRight="30.0dip" android:layout_gravity="center" android:layout_centerInParent="true" android:scaleType="fitXY" android:background="@mipmap/upload_btn" /> </LinearLayout>
upload_pic.xml:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" > <LinearLayout android:layout_margin="10dp" android:paddingBottom="10dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:orientation="vertical" > <Button android:id="@+id/btn_pop_album" android:layout_width="match_parent" android:layout_height="45dp" android:text="本地相册" android:background="#ffff" android:textSize="18sp" /> <Button android:id="@+id/btn_pop_camera" android:layout_width="match_parent" android:layout_height="45dp" android:text="相机拍摄" android:background="#ffff" android:textSize="18sp" /> <Button android:id="@+id/btn_pop_cancel" android:layout_width="match_parent" android:layout_height="45dp" android:layout_marginTop="10dp" android:background="#ffff" android:text="取消" android:textSize="18sp" /> </LinearLayout> </RelativeLayout>
import android.Manifest; import android.annotation.SuppressLint; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.text.TextUtils; import android.view.Gravity; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.PopupWindow; import android.widget.Toast; import java.io.File; import java.io.FileNotFoundException; import zpwmall.com.tms.R; import zpwmall.com.tms.adapter.UploadAsyncTask; import zpwmall.com.tms.constant.Contants; import zpwmall.com.tms.utils.MyApplication; public class WeightActivity extends BaseActivity { private ImageView upload_pic; private Button select_btn,upload_btn; private File photoFile = null; private Uri tempUri = null; private EditText send_weight,receive_weight; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.load_weight_item); //Toast.makeText(this, "test", Toast.LENGTH_SHORT).show(); upload_pic = (ImageView)findViewById(R.id.upload_pic); select_btn = (Button)findViewById(R.id.select_btn); upload_btn = (Button)findViewById(R.id.upload_btn); send_weight = (EditText)findViewById(R.id.send_weight); receive_weight = (EditText)findViewById(R.id.receive_weight); upload_pic.setVisibility(View.GONE); select_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showPopWindow(); } }); upload_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String send = send_weight.getText().toString(); String receive = receive_weight.getText().toString(); if(TextUtils.isEmpty(send)){ Toast.makeText(MyApplication.getContext(), R.string.pls_input_send_weight, Toast.LENGTH_SHORT).show(); return; } if(TextUtils.isEmpty(receive)){ Toast.makeText(MyApplication.getContext(), R.string.pls_input_receive_weight, Toast.LENGTH_SHORT).show(); return; } if(upload_pic.getDrawable() == null || upload_pic.getDrawable().getCurrent() == null || upload_pic.getDrawable().getCurrent().getConstantState() == null){ Toast.makeText(MyApplication.getContext(), R.string.pls_select_or_take_photo, Toast.LENGTH_SHORT).show(); return; } //String filePath = tempUri.getEncodedPath(); String filePath = getPathByUri4kitkat(MyApplication.getContext(),tempUri); final String imagePath = Uri.decode(filePath); new UploadAsyncTask(WeightActivity.this,imagePath).execute(); } }); } private void showPopWindow(){ View popView = View.inflate(this,R.layout.upload_pic,null); Button bt_album = (Button) popView.findViewById(R.id.btn_pop_album); Button bt_camera = (Button) popView.findViewById(R.id.btn_pop_camera); Button bt_cancle = (Button) popView.findViewById(R.id.btn_pop_cancel); //获取屏幕宽高 int weight = getResources().getDisplayMetrics().widthPixels; int height = getResources().getDisplayMetrics().heightPixels*1/3; final PopupWindow popupWindow = new PopupWindow(popView,weight,height); //popupWindow.setAnimationStyle(R.style.anim_popup_dir); popupWindow.setFocusable(true); //点击外部popueWindow消失 popupWindow.setOutsideTouchable(true); bt_album.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, Contants.RESULT_LOAD_IMAGE); popupWindow.dismiss(); } }); bt_camera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { takeCamera(); popupWindow.dismiss(); } }); bt_cancle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { popupWindow.dismiss(); } }); //popupWindow消失屏幕变为不透明 popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.alpha = 1.0f; getWindow().setAttributes(lp); } }); //popupWindow出现屏幕变为半透明 WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.alpha = 0.5f; getWindow().setAttributes(lp); popupWindow.showAtLocation(popView, Gravity.BOTTOM,0,50); } private void takeCamera() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Ensure that there's a camera activity to handle the intent if (takePictureIntent.resolveActivity(getPackageManager()) != null) { // Create the File where the photo should go String mTempPhotoPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator + "photo.jpeg"; photoFile = new File(mTempPhotoPath); //photoFile = createImageFile(); // Continue only if the File was successfully created if (photoFile != null) { takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); } } startActivityForResult(takePictureIntent, Contants.RESULT_CAMERA_IMAGE);//跳转界面传回拍照所得数据 } /* private File createImageFile() { File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); File image = null; try { image = File.createTempFile( generateFileName(), *//* prefix *//* ".jpg", *//* suffix *//* storageDir *//* directory *//* ); } catch (IOException e) { e.printStackTrace(); } String mCurrentPhotoPath = image.getAbsolutePath(); return image; } public static String generateFileName() { String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; return imageFileName; }*/ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK ) { if (requestCode == Contants.RESULT_LOAD_IMAGE) { Uri selectedImage = data.getData(); tempUri = selectedImage; }else if (requestCode == Contants.RESULT_CAMERA_IMAGE){ Uri uri = Uri.fromFile(photoFile); tempUri = uri; } if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { //申请WRITE_EXTERNAL_STORAGE权限 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1); }else{ try { Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(tempUri)); upload_pic.setImageBitmap(bitmap); upload_pic.setVisibility(View.VISIBLE); } catch (FileNotFoundException e) { e.printStackTrace(); } } } } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case 1: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { try { Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(tempUri)); upload_pic.setImageBitmap(bitmap); upload_pic.setVisibility(View.VISIBLE); } catch (FileNotFoundException e) { e.printStackTrace(); } } else { Toast.makeText(this, "deny", Toast.LENGTH_SHORT).show(); } return; } } super.onRequestPermissionsResult(requestCode, permissions, grantResults); } // 专为Android4.4设计的从Uri获取文件绝对路径,以前的方法已不好使 @SuppressLint("NewApi") public static String getPathByUri4kitkat(final Context context, final Uri uri) { final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; // DocumentProvider if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { if (isExternalStorageDocument(uri)) {// ExternalStorageProvider final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("primary".equalsIgnoreCase(type)) { return Environment.getExternalStorageDirectory() + "/" + split[1]; } } else if (isDownloadsDocument(uri)) {// DownloadsProvider final String id = DocumentsContract.getDocumentId(uri); final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); return getDataColumn(context, contentUri, null, null); } else if (isMediaDocument(uri)) {// MediaProvider final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; Uri contentUri = null; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } final String selection = "_id=?"; final String[] selectionArgs = new String[] { split[1] }; return getDataColumn(context, contentUri, selection, selectionArgs); } } else if ("content".equalsIgnoreCase(uri.getScheme())) {// MediaStore // (and // general) return getDataColumn(context, uri, null, null); } else if ("file".equalsIgnoreCase(uri.getScheme())) {// File return uri.getPath(); } return null; } /** * Get the value of the data column for this Uri. This is useful for * MediaStore Uris, and other file-based ContentProviders. * * @param context * The context. * @param uri * The Uri to query. * @param selection * (Optional) Filter used in the query. * @param selectionArgs * (Optional) Selection arguments used in the query. * @return The value of the _data column, which is typically a file path. */ public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = "_data"; final String[] projection = { column }; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int column_index = cursor.getColumnIndexOrThrow(column); return cursor.getString(column_index); } } finally { if (cursor != null) cursor.close(); } return null; } public static boolean isExternalStorageDocument(Uri uri) { return "com.android.externalstorage.documents".equals(uri.getAuthority()); } public static boolean isDownloadsDocument(Uri uri) { return "com.android.providers.downloads.documents".equals(uri.getAuthority()); } public static boolean isMediaDocument(Uri uri) { return "com.android.providers.media.documents".equals(uri.getAuthority()); } }
上传异步任务:
import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; import com.alibaba.fastjson.JSONObject; import java.io.File; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import zpwmall.com.tms.ui.WeightActivity; import zpwmall.com.tms.utils.MyApplication; /** * Created by Administrator on 2018/6/13. */ public class UploadAsyncTask extends AsyncTask<String, Integer, String> { private String imagePath; private WeightActivity context; public UploadAsyncTask(){} public UploadAsyncTask(WeightActivity context,String path){ this.imagePath = path; this.context = context; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... param) { OkHttpClient mOkHttpClient = new OkHttpClient(); String result = "error"; MultipartBody.Builder builder = new MultipartBody.Builder(); builder.addFormDataPart("image", imagePath, RequestBody.create(MediaType.parse("image/jpeg"), new File(imagePath))); RequestBody requestBody = builder.build(); Request.Builder reqBuilder = new Request.Builder(); Request request = reqBuilder .url("http://xx/itemUpload") .post(requestBody) .build(); Log.d("UploadAsyncTask", "请求地址 http://xx/itemUpload"); try{ Response response = mOkHttpClient.newCall(request).execute(); Log.d("UploadAsyncTask", "响应码 " + response.code()); if (response.isSuccessful()) { String resultValue = response.body().string(); Log.d("UploadAsyncTask", "响应体 " + resultValue); return resultValue; } } catch (Exception e) { e.printStackTrace(); } return result; } @Override protected void onPostExecute(String result) { JSONObject json = JSONObject.parseObject(result); Log.i("result", result); if (json.getString("ret").equals("true")) { Toast.makeText(MyApplication.getContext(), "上传成功!", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(MyApplication.getContext(), "上传失败!", Toast.LENGTH_SHORT).show(); } } }
..
相关推荐
一旦用户通过照相机拍摄或从图库中选择了一张照片,文件选择器会返回一个FileList对象,包含用户选中的文件。这时,我们可以通过JavaScript监听 `change` 事件来获取用户选择的文件。以下是一个简单的例子: ```...
以下是对"选择照片(拍照和相册)"这一主题的详细说明: 1. **拍照功能**:拍照是通过设备的摄像头捕获实时图像。这需要调用设备的相机API,例如在iOS中是AVFoundation框架,Android则是Camera或Camera2 API。开发者...
在iOS开发中,允许用户选择系统照片或者即时拍照是常见的功能,这涉及到系统提供的UIImagePickerController类。这个类提供了从用户的照片库、相机或者其他可用的媒体源选取图像或视频的能力。在这个过程中,开发者...
在Android开发中,调用相机拍照和选择相册照片是常见的功能,这涉及到Android系统级别的交互和权限管理。本文将详细讲解如何在Android Studio中实现这两个功能,并将获取的图片进行存储。 首先,我们需要在...
这种设计增加了用户选择照片的灵活性,满足了用户从不同位置查找图片的需求。 4. **相机集成**:除了从相册中选择,此组件还提供了直接调用系统相机拍照的功能。用户可以快速拍一张新照片并立即添加到选择列表中,...
- 同样使用Intent,这次类型设为`ACTION_PICK`或`ACTION_GET_CONTENT`,让用户从相册中选择照片。用户选择照片后,`onActivityResult()`会返回选中图片的Uri。 5. 权限管理: - 从Android 6.0(API级别23)开始,...
"Android-PhotoPicker照片选择器,相机拍照选取图片"是一个专为Android平台设计的组件,它简化了图片选取和拍摄的过程,提供了丰富的功能,使得开发者能够快速地集成到自己的应用中。 首先,我们要理解Android-...
在移动应用开发中,"选择本地图片和照相"是一个常见的功能需求,它涉及到用户能够从设备的图库中选取照片或直接通过相机拍摄新图片。这个功能在各种类型的App中都有广泛的应用,如社交应用、图像编辑工具、电商应用...
在IT行业中,尤其是在移动应用开发领域,"高仿微信朋友圈选择照片及拍照(GridView)"是一个常见的功能需求。这个功能涉及到用户界面(UI)设计、图片处理、文件操作以及相机访问等多个方面,对于开发者来说,理解和...
别忘了处理`UIImagePickerControllerDelegate`和`UINavigationControllerDelegate`协议,以便在用户选择照片后接收通知并进行后续操作。 接下来,我们讨论“拍照”。同样,`UIImagePickerController`也可用于此目的...
"手机图片照片选择"这一主题涵盖了用户从设备相册中挑选图片、裁剪图片以及使用相机拍照等多个环节。以下将详细介绍这些知识点: 1. 图片选择器: 在Android应用中,为了方便用户选择多张图片,开发者通常会使用...
"android 仿微信选择照片 拍照"这个项目,就是针对如何在Android应用中实现类似微信的图片选择和拍照功能进行的模拟。 首先,我们来详细讨论如何实现“选择图片”这一功能。在Android中,选择图片通常分为两步:从...
在Android开发中,图片选择和拍照是常见的功能需求,尤其对于社交、相册类应用更是不可或缺。本篇文章将深入探讨一款适用于Android原生环境的图片选择及拍照第三方库——PhotoPicker,它能很好地适配多个Android系统...
在Android应用开发中,用户可能需要从他们的设备中选择照片,这通常涉及到访问手机的相机或者相册。本文将深入探讨如何在Android应用中实现这一功能,让用户体验到拍照或从相册选取照片的能力。 首先,为了实现这个...
总的来说,这个"Android选择照片或拍照后裁剪图片Demo"涵盖了Android应用开发中常见的图片选择、裁剪以及自定义视图的技巧,对于提升用户界面的交互性和美观度有着重要的作用。通过学习和理解这个Demo,开发者可以更...
这三个组件将用于显示拍摄的照片和提供照相机拍摄功能。 ### 步骤 3:添加 TakePhotoFromCameraAction 右键点击 ActionList,选择 New Standard Action,然后选择 TakePhotoFromCameraAction。这将添加一个 ...
在Android应用开发中,"仿微信上传照片和拍照"是一个常见的功能需求,它涉及到用户界面交互、图片处理、文件操作以及网络通信等多个方面。微信作为一款流行的消息传递应用,其图片上传功能简洁高效,深受用户喜爱。...
这个开源项目正是为了帮助开发者实现类似微信的图片选择功能,包括“最近照片”、“其他相册照片”以及“拍照”这三个核心部分。源码已经被封装为一个library,方便集成到你的项目中。 首先,我们要理解如何将这个...
虽然调用摄像头拍照既方便又快捷,但并不是每一次我们都需要去当场拍一张照片的。 因为每个人的手机相册里应该都会存有许许多多张照片,直接从相册里选取...下面我们就来看一下,如何才能实现从相册中选择照片的 功能。
在Android开发中,头像裁剪功能是一项常见的需求,它允许用户通过拍照或选择已有照片来自定义他们的头像。这个过程通常涉及到多个技术点,包括相机权限管理、图像处理、UI设计以及用户交互。以下是对这个功能的详细...