package com.jxonlinecar.driver.utils;
|
|
import android.util.Log;
|
|
import androidx.annotation.NonNull;
|
|
import com.jxonlinecar.driver.base.Const;
|
import com.obs.services.ObsClient;
|
import com.obs.services.exception.ObsException;
|
import com.obs.services.model.PutObjectRequest;
|
import com.obs.services.model.PutObjectResult;
|
|
import java.io.File;
|
import java.util.UUID;
|
|
/**
|
* 上传管理器
|
*/
|
public class UploadManager {
|
private static final String TAG = "UploadManager";
|
// 创建华为云ObsClient实例
|
private ObsClient obsClient;
|
|
public UploadManager() {
|
}
|
|
/**
|
* 初始化华为云
|
*/
|
public void initHW() {
|
obsClient = new ObsClient(Const.accessKeyId, Const.accessKeySecret, Const.end_point);
|
}
|
|
/**
|
* 上传华为云,耗时操作
|
*
|
* @param file 文件
|
*/
|
public String uploadHWSync(@NonNull File file) {
|
if (obsClient == null) {
|
Log.d(TAG, "not init");
|
return null;
|
}
|
try {
|
// 文件上传
|
// localfile 为待上传的本地文件路径,需要指定到具体的文件名
|
PutObjectRequest request = new PutObjectRequest();
|
request.setBucketName(Const.bucketName);
|
String objectKey = UUID.randomUUID().toString();
|
request.setObjectKey(objectKey);
|
request.setFile(file);
|
PutObjectResult putObjectResult = obsClient.putObject(request);
|
if (putObjectResult.getStatusCode() == 200) {
|
Log.d(TAG, "putObject successfully");
|
return putObjectResult.getObjectUrl();
|
}
|
} catch (ObsException e) {
|
Log.d(TAG, "putObject failed");
|
// 请求失败,打印http状态码
|
Log.d(TAG, "HTTP Code:" + e.getResponseCode());
|
// 请求失败,打印服务端错误码
|
Log.d(TAG, "Error Code:" + e.getErrorCode());
|
// 请求失败,打印详细错误信息
|
Log.d(TAG, "Error Message:" + e.getErrorMessage());
|
// 请求失败,打印请求id
|
Log.d(TAG, "Request ID:" + e.getErrorRequestId());
|
Log.d(TAG, "Host ID:" + e.getErrorHostId());
|
e.printStackTrace();
|
} catch (Exception e) {
|
Log.d(TAG, "putObject failed");
|
// 其他异常信息打印
|
e.printStackTrace();
|
}
|
return null;
|
}
|
|
/**
|
* 释放资源
|
*/
|
public void release() {
|
if (obsClient != null) {
|
try {
|
obsClient.close();
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
}
|
obsClient = null;
|
}
|
}
|