安卓多照片上传

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);
            }
        });
    }
相关推荐
每次的天空2 小时前
Android学习总结之算法篇五(字符串)
android·学习·算法
Gracker3 小时前
Android Weekly #202513
android
张拭心5 小时前
工作九年程序员的三月小结
android·前端
每次的天空5 小时前
Flutter学习总结之Android渲染对比
android·学习·flutter
鸿蒙布道师7 小时前
鸿蒙NEXT开发土司工具类(ArkTs)
android·ios·华为·harmonyos·arkts·鸿蒙系统·huawei
智想天开7 小时前
11.使用依赖注入容器实现松耦合
android
yunteng5219 小时前
音视频(四)android编译
android·ffmpeg·音视频·x264·x265
tangweiguo030519879 小时前
(kotlin) Android 13 高版本 图片选择、显示与裁剪功能实现
android·开发语言·kotlin
匹马夕阳9 小时前
(一)前端程序员转安卓开发分析和规划建议
android·前端
Kika写代码9 小时前
【Android】UI开发:XML布局与Jetpack Compose的全面对比指南
android·xml·ui