当前位置:   article > 正文

鸿蒙 上传照片_鸿蒙js做上传图片

鸿蒙js做上传图片
package com.cmmboy.xzwp.ability;

import com.bumptech.glide.Glide;
import com.cmmboy.xzwp.ResourceTable;
import com.cmmboy.xzwp.bean.ImageBean;
import com.cmmboy.xzwp.net.RetrofitManagement;
import com.cmmboy.xzwp.net.Wan;
import com.cmmboy.xzwp.utils.LogUtils;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.window.service.Window;
import ohos.app.Context;
import ohos.data.resultset.ResultSet;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.io.File;

import static ohos.bundle.IBundleManager.PERMISSION_GRANTED;


public class AboutAbility extends FractionAbility {
    static final HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x0001, "选择图片测试");
    Image image;
    private final int imgRequestCode = 1123;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_about);
        Window window = getWindow();
        window.setStatusBarColor(Color.rgb(26, 159, 53));
        window.setStatusBarVisibility(Component.VISIBLE);
        Image backView = findComponentById(ResourceTable.Id_backView);
        Text title = findComponentById(ResourceTable.Id_title);
        title.setText("关于");
        backView.setClickedListener(component -> terminateAbility());

        image = findComponentById(ResourceTable.Id_test);

        //获取存储权限
        requestPermissionsFromUser(new String[]{"ohos.permission.READ_USER_STORAGE"}, imgRequestCode);


        image.setClickedListener(component -> {
            choosePic();
        });


    }

    /**
     * 权限回调
     *
     * @param requestCode  requestCode
     * @param ss           ss
     * @param grantResults grantResults
     */
    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] ss, int[] grantResults) {
        super.onRequestPermissionsFromUserResult(requestCode, ss, grantResults);
        if (requestCode != 0) {
            choosePic();
            return;
        }
        boolean isHavePermission = false;
        for (int num = 0; num < ss.length; num++) {
            isHavePermission = grantResults[num] == PERMISSION_GRANTED;
        }
        if (isHavePermission) {
            restart();
        }

    }

    private void choosePic() {
        Intent intent = new Intent();
        Operation opt = new Intent.OperationBuilder().withAction("android.intent.action.GET_CONTENT").build();
        intent.setOperation(opt);
        intent.addFlags(Intent.FLAG_NOT_OHOS_COMPONENT);
        intent.setType("image/*");
        startAbilityForResult(intent, imgRequestCode);
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {

        if (resultData != null && requestCode == imgRequestCode) {
            //选择的Img对应的Uri
            String chooseImgUri = resultData.getUriString();
            HiLog.info(label, "选择图片getScheme:" + chooseImgUri.substring(chooseImgUri.lastIndexOf('/')));
            //定义数据能力帮助对象
            DataAbilityHelper helper = DataAbilityHelper.creator(getContext());
            //定义图片来源对象
            ImageSource imageSource = null;
            //获取选择的Img对应的Id
            String chooseImgId = null;
            //如果是选择文件则getUriString结果为content://com.android.providers.media.documents/document/image%3A30,其中%3A是":"的URL编码结果,后面的数字就是image对应的Id
            //如果选择的是图库则getUriString结果为content://media/external/images/media/30,最后就是image对应的Id
            //这里需要判断是选择了文件还是图库
            if (chooseImgUri.lastIndexOf("%3A") != -1) {
                chooseImgId = chooseImgUri.substring(chooseImgUri.lastIndexOf("%3A") + 3);
            } else {
                chooseImgId = chooseImgUri.substring(chooseImgUri.lastIndexOf('/') + 1);
            }
            //获取图片对应的uri,由于获取到的前缀是content,我们替换成对应的dataability前缀
            Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, chooseImgId);
            HiLog.info(label, "选择图片dataability路径:" + uri.toString()); //dataability:///media/external/images/media/57562


            Glide.with(AboutAbility.this)
                    .load(uri.toString())
                    .into(image);

            //  转换dataability:///media/external/images/media/30为/storage/emulated/0/DCIM/YIIoT/5769014/20220516162557036.jpg
            String imagePath = searchImages(AboutAbility.this, uri);
            HiLog.info(label, "选择图片imagePath路径:" + imagePath);
            getNewsNet(imagePath);
        }
    }

    // 转换dataability:///media/external/images/media/30为/storage/emulated/0/DCIM/YIIoT/5769014/20220516162557036.jpg
    private static String searchImages(Context context, Uri contentUri) {
        DataAbilityHelper helper = DataAbilityHelper.creator(context);
        ResultSet resultSet = null;
        try {
            resultSet = helper.query(contentUri, new String[]{AVStorage.Images.Media.ID, AVStorage.Images.Media.DISPLAY_NAME, AVStorage.Images.Media.DATA}, null);
            int columnIndexForName = resultSet.getColumnIndexForName(AVStorage.Images.Media.DATA);
            resultSet.goToFirstRow();
            return resultSet.getString(columnIndexForName);
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        } finally {
            if (resultSet != null) {
                resultSet.close();
            }
        }
        return null;
    }

    private void getNewsNet(String imgPath) {

        LogUtils.d("上传的文件名: " + imgPath);
        File file = new File(imgPath);

        RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        //参数添加
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        builder.addFormDataPart("file", file.getName(), body);
        MultipartBody.Part part = builder.build().part(0);

        RetrofitManagement.getInstance().create(Wan.class).uploadFiles(part).enqueue(new Callback<ImageBean>() {
            @Override
            public void onResponse(Call<ImageBean> call, Response<ImageBean> response) {
                if (response.body().getCode() == 200) {
                    HiLog.info(label, "上传图片返回的数据===>" + response.body().getImgUrl());
                } else {

                }

            }

            @Override
            public void onFailure(Call<ImageBean> call, Throwable throwable) {

            }


        });
    }

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/296957
推荐阅读
相关标签
  

闽ICP备14008679号