安卓文件上传照片单张及多张照片上传实现

一、首先导入对应库

//网络请求库
implementation 'com.squareup.okhttp3:okhttp:3.9.0'
   //Gson解析
implementation 'com.google.code.gson:gson:2.10.1'

二、然后就是们实现上传方法  UploaderTool.java

import android.util.Log;


import com.google.gson.Gson;


import java.io.File;
import java.io.IOException;
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 onResponse(String url);
        void onFailure(String error);
    }

    private static final OkHttpClient client = new OkHttpClient();

    /**
     * 照片上传
     * @param serverUrl 服务器地址
     * @param token 令牌token
     * @param filePaths 文件路径,这支持多个文件
     * @param callback 回调
     */
    public static void uploadFile(final String serverUrl, String token, List<String> filePaths, final UploadFileCallback callback) {

        final CountDownLatch latch = new CountDownLatch(filePaths.size());

        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(mediaType, file);
                MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
                builder.addFormDataPart("file", file.getName(), fileBody);

                RequestBody requestBody = builder.build();

                // 在构建 Request 对象时添加 token 参数到请求头部
                Request request = new Request.Builder()
                        .url(serverUrl)
                        .addHeader("Authorization", token)
                        .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();
                                Gson gson = new Gson();
                                FileBen fileBen = gson.fromJson(responseStr, FileBen.class);

                                Log.d("解析服务器返回的结果:", responseStr);
                                try {
                                    callback.onResponse(fileBen.getUrl());
                                } finally {
                                    latch.countDown();
                                }
                            }
                        }
                    }
                });
            }
        }


    }
}

这里我把返回实体一起给出,具体实体已自己项目为准 FileBen.java

package com.example.registrationsystem_android.personal;

public class FileBen {
    /**
     * msg : 操作成功
     * fileName : /profile/upload/2024/04/16/avatar_20240416013601A002.jpg
     * code : 200
     * newFileName : avatar_20240416013601A002.jpg
     * url : http://test-api.setvoid.com:8080/profile/upload/2024/04/16/avatar_20240416013601A002.jpg
     * originalFilename : avatar.jpg
     */

    private String msg;
    private String fileName;
    private int code;
    private String newFileName;
    private String url;
    private String originalFilename;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getNewFileName() {
        return newFileName;
    }

    public void setNewFileName(String newFileName) {
        this.newFileName = newFileName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getOriginalFilename() {
        return originalFilename;
    }

    public void setOriginalFilename(String originalFilename) {
        this.originalFilename = originalFilename;
    }
}

 

最后就是调用了,调用方式,在我们Fragment或者Activity中直接调用即可

例如下

    private void setAvatarUploadData(String path) {

        String user_img_path = ImageCompressor.compressImage(PersonalInfoActivity.this, path);
        List<String> filePaths = new ArrayList<>();
        filePaths.add(user_img_path);
        UploaderTool.uploadFile(Constants.getHost() + "/common/upload", User.getInstance(PersonalInfoActivity.this).getToken(), filePaths, new UploaderTool.UploadFileCallback() {
            @Override
            public void onResponse(String url) {
                Log.d("选择上传的照片,",  url);
             
            }

            @Override
            public void onFailure(String error) {
                ToastUtils.ShowToast(PersonalInfoActivity.this, error);
            }
        });


    }

 

相关推荐

  1. 文件照片照片实现

    2024-07-12 16:16:01       18 阅读
  2. uniapp 图片到django后端

    2024-07-12 16:16:01       50 阅读
  3. 文件

    2024-07-12 16:16:01       51 阅读
  4. 利用CameraX 拍照获这照片的exif信息

    2024-07-12 16:16:01       39 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 16:16:01       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 16:16:01       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 16:16:01       57 阅读
  4. Python语言-面向对象

    2024-07-12 16:16:01       68 阅读

热门阅读

  1. 编译Linux内核, 制作迷你系统并在虚拟机里运行

    2024-07-12 16:16:01       21 阅读
  2. 力扣1209.删除字符串中的所有相邻重复项 II

    2024-07-12 16:16:01       20 阅读
  3. Python使用总结之jieba形容词提取详解

    2024-07-12 16:16:01       22 阅读
  4. postman接口测试工具详解

    2024-07-12 16:16:01       22 阅读
  5. 迅为RK3568手册上新 | RK3568开发板NPU例程测试

    2024-07-12 16:16:01       21 阅读
  6. Yolo的离线运行

    2024-07-12 16:16:01       24 阅读
  7. 2024.07.04校招 实习 内推 面经

    2024-07-12 16:16:01       20 阅读
  8. 从零开始学习嵌入式----C语言指针函数

    2024-07-12 16:16:01       18 阅读