Android本地选择照片或视频上传到服务器

1.创建标识码

    val PICK_PHOTO = 102  //图片
    val PHOTO_VIDEO= 103  //视频

2.创建控件点击事件

R.id.material_add_btn_put -> {
    
    
                when (type) {
    
    
                    1 -> {
    
    
                        //上传视频
                        val intent = Intent()
                        intent.type = "video/*"
                        intent.action = Intent.ACTION_GET_CONTENT
                        intent.addCategory(Intent.CATEGORY_OPENABLE)
                        startActivityForResult(intent, PHOTO_VIDEO)
                    }
                    2 -> {
    
    
                        //上传图片
                        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
                        intent.addCategory(Intent.CATEGORY_OPENABLE)
                        intent.type = "image/*"
                        startActivityForResult(intent, PICK_PHOTO)
                    }
                }
            }

3.返回事件处理

override fun onActivityResult(requestCode: Int, resultCode: Int, data1: Intent?) {
    
    
        super.onActivityResult(requestCode, resultCode, data1)
        Log.e("uploadFile", "" + requestCode)
        try {
    
    
            if (data1 != null) {
    
    
            	//获取文件路径,工具类代码在下方
                val realPathFromUri: String =  UriUtils.getPath(this,data1?.data)
                Log.e("uploadFile", realPathFromUri)
                if (requestCode == PICK_PHOTO){
    
    
                    Toast.makeText(this, "图片上传中,请稍等", Toast.LENGTH_SHORT).show()
                    upload(BitmapBase64.imageToBase64(realPathFromUri))
                }else if (requestCode == PHOTO_VIDEO){
    
    
                    val file = File(realPathFromUri)
                    val player = MediaPlayer()
                    try {
    
    
                        player.setDataSource(realPathFromUri) //recordingFilePath()为音频文件的路径
                        player.prepare()
                    } catch (e: IOException) {
    
    
                        e.printStackTrace()
                    } catch (e: java.lang.Exception) {
    
    
                        e.printStackTrace()
                    }
                    val duration = player.duration.toDouble() //获取音频的时间
                    videoTime = (duration.toInt())/1000
                    Log.d("uploadFile", "### duration: $videoTime  ")
                    material_add_tv_videoTime.text = videoTime.toString()
                    player.release() //记得释放资源
                    Toast.makeText(this, "视频上传中,请稍等", Toast.LENGTH_SHORT).show()
                    uploadFile(file)
                }

            } else {
    
    
                Log.d("uploadFile", "文件损坏,请重新选择")
                Toast.makeText(this, "文件损坏,请重新选择", Toast.LENGTH_SHORT).show()
            }

        } catch (e: java.lang.Exception) {
    
    
            e.printStackTrace()
            Log.e("uploadFile", e.toString())
        }

4.图片转换工具类

public class BitmapBase64 {
    
    

    /**
     * 将图片转换成Base64编码的字符串
     */
    public static String imageToBase64(String path){
    
    
        if(TextUtils.isEmpty(path)){
    
    
            return null;
        }
        InputStream is = null;
        byte[] data = null;
        String result = null;
        try{
    
    
            is = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[is.available()];
            //写入数组
            is.read(data);
            //用默认的编码格式进行编码
            result ="data:image/jpg;base64,"+Base64.encodeToString(data,Base64.NO_WRAP); //
        }catch (Exception e){
    
    
            e.printStackTrace();
        }finally {
    
    
            if(null !=is){
    
    
                try {
    
    
                    is.close();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
            }

        }
        return result;
    }

    /**
     * bitmap转为base64
     * @param bitmap
     * @return
     */
    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
     * @param base64Data
     * @return
     */
    public static Bitmap base64ToBitmap(String base64Data) {
    
    
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }
}

5.根据Uri获得图片或视频文件路径工具类

public class UriUtils {
    
    
	
	public static String getPath(final Context context, final Uri uri) {
    
      
	  
	    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;  
	  
	    // DocumentProvider  
	    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
    
      
	        // ExternalStorageProvider  
	        if (isExternalStorageDocument(uri)) {
    
      
	            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];  
	            }  
	  
	            // TODO handle non-primary volumes  
	        }  
	        // DownloadsProvider  
	        else if (isDownloadsDocument(uri)) {
    
      
	  
	            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);  
	        }  
	        // MediaProvider  
	        else if (isMediaDocument(uri)) {
    
      
	            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);  
	        }  
	    }  
	    // MediaStore (and general)  
	    else if ("content".equalsIgnoreCase(uri.getScheme())) {
    
      
	        return getDataColumn(context, uri, null, null);  
	    }  
	    // File  
	    else if ("file".equalsIgnoreCase(uri.getScheme())) {
    
      
	        return uri.getPath();  
	    }  
	  
	    return null;  
	}  
	  
	/** 
	 * 获取数据库表中的 _data 列,即返回Uri对应的文件路径
	 */  
	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;  
	}  
	  
	  
	/** 
	 * @param uri The Uri to check. 
	 * @return Whether the Uri authority is ExternalStorageProvider. 
	 */  
	public static boolean isExternalStorageDocument(Uri uri) {
    
      
	    return "com.android.externalstorage.documents".equals(uri.getAuthority());  
	}  
	  
	/** 
	 * @param uri The Uri to check. 
	 * @return Whether the Uri authority is DownloadsProvider. 
	 */  
	public static boolean isDownloadsDocument(Uri uri) {
    
      
	    return "com.android.providers.downloads.documents".equals(uri.getAuthority());  
	}  
	  
	/** 
	 * @param uri The Uri to check. 
	 * @return Whether the Uri authority is MediaProvider. 
	 */  
	public static boolean isMediaDocument(Uri uri) {
    
      
	    return "com.android.providers.media.documents".equals(uri.getAuthority());  
	}  
 
}

附加(上传接口请求):

1.图片上传接口(基于OkGo):

   private fun upload(base64: String) {
    
    
        val json1 = JSONObject()
        json1.put("tableName", "sub_material")
        json1.put("img", base64)

        Log.d("upload121", "json1: $json1")
        val JSON: MediaType? = MediaType.parse("application/json; charset=utf-8")
        val body = RequestBody.create(JSON, json1.toString())
        Log.d("upload121", "Urls: " + Urls.UPLOAD)
        OkGo.post<String>(Urls.UPLOAD)
            .headers(
                "token",
                SharedPreferencesHelper(this).getSharedPreference(Contents.TOKEN, "") as String?
            )
            .upRequestBody(body)
            .execute(object : StringCallback() {
    
    
                override fun onSuccess(response: Response<String>) {
    
    
                    Log.e("upload121", "response: ${response.body()}")
                    try {
    
    
                        val addImageBean: AddImageBean = FastJsonUtils.getObject(
                            response.body(),
                            AddImageBean::class.java
                        )
                        if (addImageBean.code == 0) {
    
    
//                           jsonarray.remove()
                            jsonarray.put(addImageBean.data.file.fileId)
                            material_add_iv_pic.visibility = View.VISIBLE
                            size = PicKb.imageSize(base64) / 1024
                            material_add_tv_size_pic.text = size.toString()
                            Log.e("upload121", "size: $size")
                            Glide.with(this@MaterialAddActivity).load(addImageBean.data.file.url)
                                .error(
                                    R.mipmap.ic_404_hint
                                ).into(material_add_iv_pic)
                            Toast.makeText(this@MaterialAddActivity, "上传成功", Toast.LENGTH_SHORT).show()
                        } else {
    
    
                            Toast.makeText(
                                this@MaterialAddActivity,
                                addImageBean.msg,
                                Toast.LENGTH_SHORT
                            ).show()
                        }

                    } catch (e: Exception) {
    
    
                        Log.e("upload121", "registerDetection: $e")
                        Toast.makeText(
                            this@MaterialAddActivity,
                            "接口错误返回",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }

                override fun onError(response: Response<String>) {
    
    
                    super.onError(response)
                    Log.e("upload121", "onError: " + response.body())
                    Toast.makeText(this@MaterialAddActivity, "请求接口失败", Toast.LENGTH_SHORT)
                        .show()
                }
            })
    }

2.视频上传接口(基于OkGo):

private fun uploadFile(file: File) {
    
    
        val json1 = JSONObject()
        json1.put("file", file)

        Log.d("uploadFile", "json1: $json1")
        val JSON: MediaType? = MediaType.parse("application/json; charset=utf-8")
        val body = RequestBody.create(JSON, json1.toString())
        Log.d("uploadFile", "Urls: " + Urls.UPLOADVIDEO)
        OkGo.post<String>(Urls.UPLOADVIDEO)
            .headers("token", SharedPreferencesHelper(this).getSharedPreference(Contents.TOKEN, "") as String?)
            .params("file", file)
            .isMultipart(true)
            .execute(object : StringCallback() {
    
    
                override fun onSuccess(response: Response<String>) {
    
    
                    Log.e("uploadFile", "response: ${
      
      response.body()}")
                    try {
    
    
                        val fileBean: AddFileBean = FastJsonUtils.getObject(
                            response.body(),
                            AddFileBean::class.java
                        )
                        if (fileBean.code == 0) {
    
    
                            jsonarray.put(fileBean.data.file.fileId)
                            material_add_iv_pic.visibility = View.VISIBLE
                            size = (file.length() / 1024).toInt()
                            material_add_tv_size_video.text = size.toString()
                            Log.e("uploadFile", "size: $size")
                            Glide.with(this@MaterialAddActivity).load(fileBean.data.img.url).error(R.mipmap.ic_404_hint).into(material_add_iv_pic)
                            Toast.makeText(this@MaterialAddActivity, "上传成功", Toast.LENGTH_SHORT).show()
                        } else {
    
    
                            Toast.makeText(
                                this@MaterialAddActivity,
                                fileBean.msg,
                                Toast.LENGTH_SHORT
                            ).show()
                        }

                    } catch (e: Exception) {
    
    
                        Log.e("uploadFile", "registerDetection: $e")
                        Toast.makeText(
                            this@MaterialAddActivity,
                            "接口错误返回",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }

                override fun onError(response: Response<String>) {
    
    
                    super.onError(response)
                    Log.e("uploadFile", "onError: " + response.body())
                    Toast.makeText(this@MaterialAddActivity, "请求接口失败", Toast.LENGTH_SHORT)
                        .show()
                }

                override fun uploadProgress(progress: Progress?) {
    
    
                    super.uploadProgress(progress)
                     Log.e("uploadFile", "上传进度: " +progress?.fraction)
                }
            })

猜你喜欢

转载自blog.csdn.net/qq_30297763/article/details/113628828