安卓图实现图片上传

实现

首先引入依赖

    implementation 'com.squareup.okhttp3:okhttp:3.9.0'

下面是上传工具类

java 复制代码
public class UploaderTool {
    public interface UploadFileCallback {
        // 服务器响应回调方法
        void onServeResponse(String data);
        // 文件上传成功回调方法,参数为所有文件的URL拼接字符串
        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());
        // 存储每个文件的URL
        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 复制代码
//图片压缩工具类
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 = 50;

        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 复制代码
   private void setAvatarUploadData(String path) {
        String user_img_path = ImageCompressor.compressImage(this, path);
        List<String> filePaths = new ArrayList<>();
        filePaths.add(user_img_path);
        UploaderTool.uploadFile(Constant.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);

                    
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onResponse(String joinedUrls) {

            }

            @Override
            public void onFailure(String error) {
            
            }
        });
    }
相关推荐
似霰8 分钟前
安卓智能指针sp、wp、RefBase浅析
android·c++·binder
大风起兮云飞扬丶8 分钟前
Android——网络请求
android
干一行,爱一行11 分钟前
android camera data -> surface 显示
android
芊寻(嵌入式)18 分钟前
C转C++学习笔记--基础知识摘录总结
开发语言·c++·笔记·学习
WaaTong20 分钟前
《重学Java设计模式》之 原型模式
java·设计模式·原型模式
m0_7430484420 分钟前
初识Java EE和Spring Boot
java·java-ee
AskHarries22 分钟前
Java字节码增强库ByteBuddy
java·后端
一颗松鼠27 分钟前
JavaScript 闭包是什么?简单到看完就理解!
开发语言·前端·javascript·ecmascript
断墨先生27 分钟前
uniapp—android原生插件开发(3Android真机调试)
android·uni-app
有梦想的咸鱼_29 分钟前
go实现并发安全hashtable 拉链法
开发语言·golang·哈希算法