当前位置: 首页 > news >正文

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

一、首先导入对应库

//网络请求库
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() {@Overridepublic void onFailure(okhttp3.Call call, IOException e) {latch.countDown();if (callback != null) {callback.onFailure("Exception: " + e.toString());}}@Overridepublic 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() {@Overridepublic void onResponse(String url) {Log.d("选择上传的照片,",  url);}@Overridepublic void onFailure(String error) {ToastUtils.ShowToast(PersonalInfoActivity.this, error);}});}

 

http://www.lryc.cn/news/398011.html

相关文章:

  • 小白学webgl合集-import.meta.url 和 new URL() bug
  • pico+unity3d开启彩色透视
  • python常用命令
  • 使用定时器消除抖动
  • IOS热门面试题一
  • 构建LangChain应用程序的示例代码:62、如何使用Oracle AI向量搜索和Langchain构建端到端的RAG(检索增强生成)pipeline
  • ffmpeg转换MP4为gif命令
  • kotlin Flow 学习指南 (三)最终篇
  • Memcached负载均衡:揭秘高效缓存分发策略
  • 【Python实战因果推断】31_双重差分2
  • ArcGIS中使用线快速构造成面的方法
  • Spring AOP的几种实现方式
  • 字节码编程bytebuddy之实现抽象类并并添加自定义注解
  • LLM-阿里云 DashVector + ModelScope 多模态向量化实时文本搜图实战总结
  • CentOS7安装部署git和gitlab
  • 《昇思25天学习打卡营第16天|基于MindNLP+MusicGen生成自己的个性化音乐》
  • 算法学习day10(贪心算法)
  • 卡尔曼滤波Kalman Filter零基础入门到实践(上部)
  • 力扣-dfs
  • keepalived高可用集群
  • 文献翻译与阅读《Integration Approaches for Heterogeneous Big Data: A Survey》
  • 应用最优化方法及MATLAB实现——第3章代码实现
  • django的增删改查,排序,分组等常用的ORM操作
  • Leetcode Java学习记录——树、二叉树、二叉搜索树
  • 华为HCIP Datacom H12-821 卷30
  • element el-table实现表格动态增加/删除/编辑表格行,带校验规则
  • QT调节屏幕亮度
  • 实变函数精解【3】
  • JVM:SpringBoot TomcatEmbeddedWebappClassLoader
  • 蜂窝互联网接入:连接世界的无缝体验