安卓文件上传照片单张及多张照片上传实现
一、首先导入对应库
(图片来源网络,侵删)
//网络请求库 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 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 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);
}
});
}
免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!
