安卓图实现图片上传

实现

首先引入依赖

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

下面是上传工具类

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());
            }
        }
    }
}

图片压缩工具类

//图片压缩工具类
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();
    }
}

使用用法如下

   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) {
            
            }
        });
    }

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

来之梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值