一、首先导入对应库
//网络请求库
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);
}
});
}