直播源码搭建教程之获取相册中的指定一个图片后上传
直播源码搭建教程之获取相册中的指定一个图片后上传实现的相关代码
package com.example.myapplication;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import org.xutils.ex.HttpException;
import org.xutils.http.RequestParams;
import org.xutils.x;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
ProgressDialog dialogShibie;
List<File> fileArrayList;
private static final int CAMERA_CODE = 200;
private static final int ALBUM_CODE = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fileArrayList = new ArrayList<>();
dialogShibie = new ProgressDialog(this);
// upload();
takesD();
}
@Override
protected void onResume() {
super.onResume();
// takesD();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (permissions[0] == Manifest.permission.CAMERA) {
openCamera();
} else if (permissions[0] == Manifest.permission.WRITE_EXTERNAL_STORAGE) {
openAlbum();
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_CODE) {
if (resultCode == RESULT_OK) {
try {
//Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver()
// .openInputStream(mImageUri));
//img.setImageBitmap(bitmap);
//处理照相之后的结果并上传
uploadOk(mFile);
} catch (Exception e) {
e.printStackTrace();
}
}
} else if (requestCode == ALBUM_CODE) {
//相册
if (resultCode == RESULT_OK) {
Uri imageUri = data.getData();
//处理uri,7.0以后的fileProvider 把URI 以content provider 方式 对外提供的解析方法
File file = getFileFromUri(imageUri, this);
// String parent = file.getParent();
// List<String> filesAllName = getFilesAllName(parent);
Log.e("wy", "getParent: "+ filesAllName.get(0) );
// for (int i = 0; i <filesAllName.size() ; i++) {
// Log.e("wy", "onActivityResult: "+filesAllName.get(i) );
// File f = new File(parent, filesAllName.get(i));
// }
if (file.exists()) {
updateFile(file);
}
}
}
}
public List<String> getFilesAllName(String path) {
File file=new File(path);
File[] files=file.listFiles();
if (files == null){Log.e("error","空目录");return null;}
List<String> s = new ArrayList<>();
for(int i =0;i<files.length;i++){
s.add(files[i].getName());
}
return s;
}
public File getFileFromUri(Uri uri, Context context) {
if (uri == null) {
return null;
}
Log.e("wy", "getScheme: "+uri.getScheme() );
switch (uri.getScheme()) {
case "content":
return getFileFromContentUri(uri, context);
case "file":
return new File(uri.getPath());
default:
return null;
}
}
/**
* 通过内容解析中查询uri中的文件路径
*/
private File getFileFromContentUri(Uri contentUri, Context context) {
if (contentUri == null) {
return null;
}
File file = null;
String filePath;
String[] filePathColumn = {MediaStore.MediaColumns.DATA};
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(contentUri, filePathColumn, null,
null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
Log.e("wy", "filePath: "+filePath);
cursor.close();
if (!TextUtils.isEmpty(filePath)) {
file = new File(filePath);
}
}
return file;
}
/**
* 文件上传
*/
private void uploadOk(File file) {
}
private void updateFile(File file) {
//拍照获取的图片
fileArrayList.clear();
fileArrayList.add(file);
List<File> mFile = fileArrayList;
// 存到本地的图片
// String sdPath = getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "/a/test.jpg";
// File mFile=new File(sdPath);
dialogShibie.setTitle("上传中");
dialogShibie.show();
// Log.e("wy1", "开始上传图片的时间: " + TimeUtil.stampToDate(System.currentTimeMillis() + ""));
RequestParams params = new RequestParams("http://192.168.176.119/uploadFile");
// params.setConnectTimeout(5000);
// 有上传文件时使用multipart表单, 否则上传原始文件流.
params.setMultipart(true);
// 上传文件方式 2 /mnt/internal_sd/FtrendCrashLog/th.jpg
params.addBodyParameter("files", mFile);
// params.addBodyParameter("file", bitmapUse);
Log.e("wy", "params: " + params);
org.xutils.common.Callback.Cancelable cancelable
= x.http().post(params, new org.xutils.common.Callback.CommonCallback<String>() {
@Override
public void onSuccess(String result) {
Log.e("wy1", "上传图片成功: " );
dialogShibie.dismiss();
Toast.makeText(x.app(), "上传图片成功", Toast.LENGTH_SHORT).show();
Log.e("wy", "result: " + result);
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
//Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
if (ex instanceof HttpException) { // 网络错误
HttpException httpEx = (HttpException) ex;
int responseCode = httpEx.getCode();
String responseMsg = httpEx.getMessage();
String errorResult = httpEx.getResult();
Log.e("wy", "responseCode " +responseCode);
if (responseCode == 404) {
dialogShibie.dismiss();
Toast.makeText(x.app(), "ip地址错误", Toast.LENGTH_LONG).show();
}
// ...
} else { // 其他错误
// ...
}
// dialogShibie.dismiss();
Log.e("wy", "请求上传图片地址错误: " + ex.getMessage());
// Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
}
@Override
public void onCancelled(CancelledException cex) {
Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
}
@Override
public void onFinished() {
dialogShibie.dismiss();
Log.e("wy", "本次请求完全结束 ");
}
});
}
private File mFile;
private Uri mImageUri;
private void openCamera() {
//创建文件用于保存图片
mFile = new File(getExternalCacheDir(), System.currentTimeMillis() + ".jpg");
if (!mFile.exists()) {
try {
mFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//适配7.0
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
mImageUri = Uri.fromFile(mFile);
} else {
//第二个参数要和清单文件中的配置保持一致
mImageUri = FileProvider.getUriForFile(this, "com.baidu.upload.provider", mFile);
}
//启动相机
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);//将拍照图片存入mImageUri
startActivityForResult(intent, CAMERA_CODE);
}
private void takesD() {
//权限判断
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
openAlbum();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission
.WRITE_EXTERNAL_STORAGE}, 100);
}
}
private void openAlbum() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(intent, ALBUM_CODE);
}
public List<File> saveBitmap() {
Log.e("wy", "开始保存");
//生成一个文件,存储我们将来拍照的照片
// String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/a/" ;
String sdPath = getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "/a/";
// String sdPath = "/mnt/sdcard/Internal Memory" ;
// File file = new File(sdPath);
// Log.e("wy", "绝对文件路径: " + file.getAbsoluteFile());
// Log.e("wy", "文件名: " + file.getName());
// if (!file.exists()) {
// file.mkdirs();
// Log.e("wy", "创建文件夹,路径:" + file.getPath());
// }
// String mFileName = System.currentTimeMillis() + ".jpg";
String mFileName = "a.jpg";
String mFileName1 = "b.jpg";
String mFileName2 = "c.jpg";
String mFileName3 = "d.jpg";
String mFileName4 = "e.jpg";
Log.e("wy", "保存文件名称: " + mFileName);
File f = new File(sdPath, mFileName);
File f2 = new File(sdPath, mFileName1);
File f3 = new File(sdPath, mFileName2);
File f4 = new File(sdPath, mFileName3);
File f5 = new File(sdPath, mFileName4);
fileArrayList.clear();
fileArrayList.add(f);
fileArrayList.add(f2);
fileArrayList.add(f3);
// fileArrayList.add(f4);
// fileArrayList.add(f5);
// fileArrayList.add(f2);
return fileArrayList;
}
private void upload() {
//拍照获取的图片
List<File> mFile = saveBitmap();
// 存到本地的图片
// String sdPath = getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "/a/test.jpg";
// File mFile=new File(sdPath);
dialogShibie.setTitle("上传中");
dialogShibie.show();
// Log.e("wy1", "开始上传图片的时间: " + TimeUtil.stampToDate(System.currentTimeMillis() + ""));
RequestParams params = new RequestParams("http://192.168.176.119/uploadFile");
// params.setConnectTimeout(5000);
// 有上传文件时使用multipart表单, 否则上传原始文件流.
params.setMultipart(true);
// 上传文件方式 2 /mnt/internal_sd/FtrendCrashLog/th.jpg
params.addBodyParameter("files", mFile);
// params.addBodyParameter("file", bitmapUse);
Log.e("wy", "params: " + params);
org.xutils.common.Callback.Cancelable cancelable
= x.http().post(params, new org.xutils.common.Callback.CommonCallback<String>() {
@Override
public void onSuccess(String result) {
Log.e("wy1", "上传图片成功: " );
dialogShibie.dismiss();
// Toast.makeText(x.app(), "查到任务ID", Toast.LENGTH_SHORT).show();
Log.e("wy", "result: " + result);
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
//Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
if (ex instanceof HttpException) { // 网络错误
HttpException httpEx = (HttpException) ex;
int responseCode = httpEx.getCode();
String responseMsg = httpEx.getMessage();
String errorResult = httpEx.getResult();
Log.e("wy", "responseCode " +responseCode);
if (responseCode == 404) {
dialogShibie.dismiss();
Toast.makeText(x.app(), "ip地址错误", Toast.LENGTH_LONG).show();
}
// ...
} else { // 其他错误
// ...
}
// dialogShibie.dismiss();
Log.e("wy", "请求上传图片地址错误: " + ex.getMessage());
// Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
}
@Override
public void onCancelled(CancelledException cex) {
Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
}
@Override
public void onFinished() {
dialogShibie.dismiss();
Log.e("wy", "本次请求完全结束 ");
}
});
}
}
以上就是 直播源码搭建教程之获取相册中的指定一个图片后上传实现的相关代码,更多内容欢迎关注之后的文章