import android.util.Log;
import com.zx.eselected.client.toools.ImageCompressor;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
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 onServeResponse(String data);
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());
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());
}
}
}
}
图片压缩工具类
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* image compression tool
*/
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 = 100;
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();
}
}
注意
这里不要忘记添加
依赖
implementation 'com.squareup.okhttp3:okhttp:3.9.0'
和权限
<uses-permission android:name="android.permission.INTERNET" />
使用案例
在Activity使用
private void setAvatarUploadData(String path) {
String user_img_path = ImageCompressor.compressImage(AcceptanceEngineerMemberEditorActivity.this, path);
List<String> filePaths = new ArrayList<>();
filePaths.add(user_img_path);
UploaderTool.uploadFile(Constants.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);
// Message msg = new Message();
// msg.what = 1;
// msg.obj = fileUrl;
// handler.sendMessage(msg);
newAcceptanceEngineerMemberEditorPresenter.setAvatarData(fileUrl);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onResponse(String joinedUrls) {
}
@Override
public void onFailure(String error) {
ToastUtils.ShowToast(AcceptanceEngineerMemberEditorActivity.this, error);
}
});
}
标签:安卓多,String,okhttp3,照片,callback,new,import,null,上传
From: https://blog.csdn.net/qq_41733851/article/details/137562450