实现
首先引入依赖
implementation 'com.squareup.okhttp3:okhttp:3.9.0'
下面是上传工具类
java
public class UploaderTool {
public interface UploadFileCallback {
// 服务器响应回调方法
void onServeResponse(String data);
// 文件上传成功回调方法,参数为所有文件的URL拼接字符串
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());
// 存储每个文件的URL
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
//图片压缩工具类
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 = 50;
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
private void setAvatarUploadData(String path) {
String user_img_path = ImageCompressor.compressImage(this, path);
List<String> filePaths = new ArrayList<>();
filePaths.add(user_img_path);
UploaderTool.uploadFile(Constant.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);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onResponse(String joinedUrls) {
}
@Override
public void onFailure(String error) {
}
});
}