直播原始碼搭建教程之獲取相簿中的指定一個圖片後上傳

zhibo系統開發發表於2021-10-09

直播原始碼搭建教程之獲取相簿中的指定一個圖片後上傳實現的相關程式碼

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", "本次請求完全結束 ");
            }
        });
    }
}


以上就是 直播原始碼搭建教程之獲取相簿中的指定一個圖片後上傳實現的相關程式碼,更多內容歡迎關注之後的文章


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69978258/viewspace-2795094/,如需轉載,請註明出處,否則將追究法律責任。

相關文章