安卓多照片上传

java 复制代码
import android.util.Log;

import com.zx.eselected.client.toools.ImageCompressor;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class UploaderTool {
    public interface UploadFileCallback {
        void onServeResponse(String data);
        void onResponse(String joinedUrls);
        void onFailure(String error);
    }

    private static final OkHttpClient client = new OkHttpClient();

    public static void uploadFile(final String serverUrl, List<String> filePaths, final UploadFileCallback callback) {



        final CountDownLatch latch = new CountDownLatch(filePaths.size());
        final List<String> fileUrls = new ArrayList<>();

        for (String filePath : filePaths) {
            if (filePath == null) {
                latch.countDown();
                if (callback != null) {
                    callback.onFailure("文件路径为空");
                    return;
                }
            }

            File file = new File(filePath);
            if (!file.exists() || file.isDirectory()) {
                latch.countDown();
                if (callback != null) {
                    callback.onFailure("文件未找到或是一个目录: " + filePath);
                    return;
                }
            } else {
                MediaType mediaType = MediaType.parse("application/octet-stream");
                RequestBody fileBody = RequestBody.create(file, mediaType);
                MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
                builder.addFormDataPart("file", file.getName(), fileBody);

                RequestBody requestBody = builder.build();
                Request request = new Request.Builder().url(serverUrl).post(requestBody).build();

                client.newCall(request).enqueue(new okhttp3.Callback() {
                    @Override
                    public void onFailure(okhttp3.Call call, IOException e) {
                        latch.countDown();
                        if (callback != null) {
                            callback.onFailure("Exception: " + e.toString());
                        }
                    }

                    @Override
                    public void onResponse(okhttp3.Call call, Response response) throws IOException {
                        try (ResponseBody responseBody = response.body()) {
                            if (!response.isSuccessful() || responseBody == null) {
                                latch.countDown();
                                if (callback != null) {
                                    callback.onFailure("Upload failed: " + response);
                                }
                            } else {
                                String responseStr = responseBody.string();
                                Log.d("解析服务器返回的结果:", responseStr);
                                try {
                                    JSONObject jsonObject = new JSONObject(responseStr);
                                    if (jsonObject.has("data") && jsonObject.getJSONObject("data").has("fileUrl")) {
                                        String fileUrl = jsonObject.getJSONObject("data").getString("fileUrl");
                                        synchronized (fileUrls) {
                                            fileUrls.add(fileUrl);
                                        }
                                    }
                                    if (callback != null) {
                                        callback.onServeResponse(responseStr);
                                    }
                                } catch (JSONException e) {
                                    if (callback != null) {
                                        callback.onFailure("JSON parsing error: " + e.toString());
                                    }
                                } finally {
                                    latch.countDown();
                                }
                            }
                        }
                    }
                });
            }
        }

        try {
            latch.await();
            String joinedUrls = String.join(",", fileUrls);
            if (callback != null) {
                callback.onResponse(joinedUrls);
            }
        } catch (InterruptedException e) {
            if (callback != null) {
                callback.onFailure("Interrupted exception: " + e.toString());
            }
        }
    }
}

图片压缩工具类

java 复制代码
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * image compression tool
 */
public class ImageCompressor {

    public static String compressImage(Context context, String imagePath) {
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
        if (bitmap == null) {
            return null;
        }

        File compressedImageFile = new File(context.getCacheDir(), "avatar.jpg");

        int quality = 100;

        try (FileOutputStream fos = new FileOutputStream(compressedImageFile)) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fos);
            fos.flush();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        return compressedImageFile.getAbsolutePath();
    }
}

注意

这里不要忘记添加

依赖

java 复制代码
    implementation 'com.squareup.okhttp3:okhttp:3.9.0'

和权限

java 复制代码
    <uses-permission android:name="android.permission.INTERNET" />

使用案例

在Activity使用

java 复制代码
private void setAvatarUploadData(String path) {
        String user_img_path = ImageCompressor.compressImage(AcceptanceEngineerMemberEditorActivity.this, path);
        List<String> filePaths = new ArrayList<>();
        filePaths.add(user_img_path);
        UploaderTool.uploadFile(Constants.FILE_UPLOAD, filePaths, new UploaderTool.UploadFileCallback() {
            @Override
            public void onServeResponse(String data) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    if (jsonObject.has("data") && jsonObject.getJSONObject("data").has("fileUrl")) {
                        String fileUrl = jsonObject.getJSONObject("data").getString("fileUrl");
                        Log.d("选择上传的照片,", fileUrl);
//                        Message msg = new Message();
//                        msg.what = 1;
//                        msg.obj = fileUrl;
//                        handler.sendMessage(msg);
                        newAcceptanceEngineerMemberEditorPresenter.setAvatarData(fileUrl);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onResponse(String joinedUrls) {

            }

            @Override
            public void onFailure(String error) {
                ToastUtils.ShowToast(AcceptanceEngineerMemberEditorActivity.this, error);
            }
        });
    }
相关推荐
Winston Wood2 小时前
Android Parcelable和Serializable的区别与联系
android·序列化
清风徐来辽2 小时前
Android 项目模型配置管理
android
帅得不敢出门2 小时前
Gradle命令编译Android Studio工程项目并签名
android·ide·android studio·gradlew
problc3 小时前
Flutter中文字体设置指南:打造个性化的应用体验
android·javascript·flutter
帅得不敢出门13 小时前
安卓设备adb执行AT指令控制电话卡
android·adb·sim卡·at指令·电话卡
我又来搬代码了15 小时前
【Android】使用productFlavors构建多个变体
android
德育处主任16 小时前
Mac和安卓手机互传文件(ADB)
android·macos
芦半山16 小时前
Android“引用们”的底层原理
android·java
迃-幵17 小时前
力扣:225 用队列实现栈
android·javascript·leetcode
大风起兮云飞扬丶17 小时前
Android——从相机/相册获取图片
android