Android实现多图上传工具类

来个用okhttp3实现的图片上传,方便以后使用

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;

import com.google.gson.reflect.TypeToken;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import tnnetframework.tnobject.BaseServerResponse;

/**
 * Create by zhangdong 2019/3/1
 */
public class ImageUploadManager {
    private static final String TAG = ImageUploadManager.class.getSimpleName();
    private static final String PATH = "tek/image/";
    private static ImageUploadManager sInstance;

    private ImageUploadManager() {
    }

    public static ImageUploadManager instance() {
        if (sInstance == null) {
            synchronized (ImageUploadManager.class) {
                if (sInstance == null) {
                    sInstance = new ImageUploadManager();
                }
            }
        }
        return sInstance;
    }

    public void imageUpLoadRequest(Context context, String requestUrl, ArrayList<String> localPath, final ImageUploadListener callBack) {
        MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS);
        OkHttpClient client = clientBuilder.build();

        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        for (String path : localPath) {
            String suffix = checkPictureFormat(path);
            String fileName = PATH + UUID.randomUUID().toString() + (suffix != null ? suffix : "");
            Bitmap bitmap;
            try {
                bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), Uri.parse(path));
                builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"files\"; filename=\"" + fileName + "\""),
                        RequestBody.create(MEDIA_TYPE_PNG, BitmapUtil.bitmapBytes(bitmap, true)));
            } catch (Exception e) {
                LogUtil.e(TAG, e.toString());
            }
        }

        final MultipartBody requestBody = builder.build();
        //构建请求
        final Request request = new Request.Builder()
                .header("sessionId", “sessiodId)
                .url(requestUrl)//地址
                .post(requestBody)//添加请求体
                .build();
        client.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                callBack.onFailed(e.getMessage());
                LogUtil.e(TAG, "upload failed :e.getLocalizedMessage() = " + e.getLocalizedMessage());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull okhttp3.Response response) {
                if (response.body() != null) {
                    try {
                        BaseServerResponse result = JsonUtil.decode(response.body().string(), BaseServerResponse.class);
                        if (result != null) {
                            List<ImageFileUploadOutput> resultBean = JsonUtil.decode(result.data, new TypeToken<List<ImageFileUploadOutput>>() {
                            }.getType());
                            callBack.onSuccess(resultBean);
                        } else {
                            callBack.onFailed("data decode error");
                        }
                    } catch (Exception e) {
                        LogUtil.e(TAG, "upload failed :e.getLocalizedMessage() = " + e.getMessage());
                        callBack.onFailed(e.getMessage());
                    }
                }
            }
        });

    }

    /**
     * 图片类型
     *
     * @param path 图片路径
     * @return  图片类型
     */
    private String checkPictureFormat(String path) {
        Pattern r = Pattern.compile("\\.(jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF|webp|WEBP)$");
        Matcher matcher = r.matcher(path);
        if (matcher.find()) {
            return path.substring(matcher.start());
        } else {
            LogUtil.w(TAG, "picture format not found, only support jpg|png|gif|webp");
            return null;
        }
    }

    /**
     * Bitmap转换成byte[]并且进行压缩
     *
     * @param bitmap
     * @return 压缩后的图片
     */
    private byte[] bitmapBytes(Bitmap bitmap, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
        if (needRecycle) {
            bitmap.recycle();
        }
        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            LogUtil.w(LOG_TAG, e.getMessage());
        }
        return result;
    }

    public interface ImageUploadListener {
        void onSuccess(List<ImageFileUploadOutput> result);

        void onFailed(String reason);
    }
}

Json解析工具类

import java.lang.reflect.Type;

import com.google.gson.Gson;
import com.google.gson.JsonParseException;


public class JsonUtil {

    private static final Gson GSON = new Gson();

    /**
     * 将json字符串转换成相应的对象
     *
     * @param jsonString json字符串
     * @param classOfT   对象类型的class
     * @param <T>        对象的类型
     * @return 转换后的对象
     * @throws JsonParseException if json is not a valid representation for an object of type classOfT
     */
    public static <T> T decode(String jsonString, Class<T> classOfT) throws RuntimeException {
        return GSON.fromJson(jsonString, classOfT);
    }

    /**
     * 将json字符串转换成相应的对象
     *
     * @param jsonString json字符串
     * @param typeOfT    对象类型的type
     * @param <T>        对象的类型
     * @return 转换后的对象
     * @throws JsonParseException if json is not a valid representation for an object of type typeOfT
     */
    public static <T> T decode(String jsonString, Type typeOfT) throws RuntimeException {
        return GSON.fromJson(jsonString, typeOfT);
    }

    /**
     * 将已经从json转换后的对象(通常是一个Map)转换成对应Bean的对象实例
     *
     * @param object  一个转json换中的过程对象,通常是一个Map,若传值为null,则返回null
     * @param typeOfT 要转换的对象类型的type
     * @param <T>     要转换的对象类型
     * @return 转换后的对象
     * @throws JsonParseException if object is not a valid representation for an object of type typeOfT
     */
    public static <T> T decode(Object object, Type typeOfT) throws RuntimeException {
        String jsonString = GSON.toJson(object);
        return GSON.fromJson(jsonString, typeOfT);
    }

    /**
     * 将一个JavaBean转换成json字符串
     *
     * @param object 待转换的对象
     * @return json字符串
     * @throws JsonParseException if there was a problem while parsing object.
     */
    public static String encode(Object object) throws RuntimeException {
        return GSON.toJson(object);
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值