安卓多照片上传

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);
            }
        });
    }
相关推荐
bianshaopeng1 小时前
android 原生加载pdf
android·pdf
hhzz1 小时前
Linux Shell编程快速入门以及案例(Linux一键批量启动、停止、重启Jar包Shell脚本)
android·linux·jar
火红的小辣椒2 小时前
XSS基础
android·web安全
勿问东西4 小时前
【Android】设备操作
android
五味香4 小时前
C++学习,信号处理
android·c语言·开发语言·c++·学习·算法·信号处理
图王大胜6 小时前
Android Framework AMS(01)AMS启动及相关初始化1-4
android·framework·ams·systemserver
工程师老罗8 小时前
Android Button “No speakable text present” 问题解决
android
小雨cc5566ru9 小时前
hbuilderx+uniapp+Android健身房管理系统 微信小程序z488g
android·微信小程序·uni-app
小雨cc5566ru10 小时前
微信小程序hbuilderx+uniapp+Android 新农村综合风貌旅游展示平台
android·微信小程序·uni-app
小雨cc5566ru10 小时前
小程序 uniapp+Android+hbuilderx体育场地预约管理系统的设计与实现
android·小程序·uni-app