七牛上传工具类
public class UploadFileHelper {
static UploadFileHelper uploadFileHelper;
UploadManager uploadManager;
//七牛请求数据
QiniuToken.Map token;
//压缩文件存放路径
final String STOREPATH = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "network";
boolean isUploading = false;
private UploadFileHelper() {
Configuration config = new Configuration.Builder()
.connectTimeout(90) // 链接超时。默认90秒
.useHttps(false) // 是否使用https上传域名
.useConcurrentResumeUpload(true) // 使用并发上传,使用并发上传时,除最后一块大小不定外,其余每个块大小固定为4M,
.concurrentTaskCount(3) // 并发上传线程数量为3
.responseTimeout(90) // 服务器响应超时。默认90秒
//.recorder(recorder) // recorder分片上传时,已上传片记录器。默认null
//.recorder(recorder, keyGen) // keyGen 分片上传时,生成标识符,用于片记录器区分是那个文件的上传记录
.zone(FixedZone.zone2) // 设置区域,不指定会自动选择。指定不同区域的上传域名、备用域名、备用IP。
.build();
// 重用uploadManager。一般地,只需要创建一个uploadManager对象
uploadManager = new UploadManager(config);
}
public static UploadFileHelper getInstance(){
if(uploadFileHelper == null){
uploadFileHelper = new UploadFileHelper();
}
return uploadFileHelper;
}
/**
* 上传文件
* @param filePath 文件路径
* @param listener 文件上传回调
*/
public void uploadFile(String filePath, UploadFileListener listener){
uploadFile(-1,filePath,listener);
}
/**
* 上传文件
* @param requestCode 文件上传回调对应码
* @param filePath 文件路径
* @param listener 文件上传回调
*/
public void uploadFile(int requestCode, String filePath, UploadFileListener listener){
uploadFile(requestCode,listener,filePath);
}
/**
*
* 上传文件
* @param listener 文件上传回调
* @param filePaths 多个文件路径
*/
public void uploadFile(UploadFileListener listener ,String... filePaths){
uploadFile(-1,listener,getFileByPath(filePaths));
}
/**
*
* 上传文件
* @param requestCode 文件上传回调对应码
* @param listener 文件上传回调
* @param filePaths 多个文件路径
*/
public void uploadFile(int requestCode, UploadFileListener listener, String... filePaths){
startUploadFile(requestCode,listener,getFileByPath(filePaths));
}
/**
* 上传文件,指定请求号
*
* @param file 文件
* @param listener 监听回调
*/
public void uploadFile(File file,UploadFileListener listener ){
uploadFile( listener,file);
}
public void uploadFile(UploadFileListener listener, File... file){
uploadFile(-1,listener,file);
}
/**
* 上传文件
*
* @param requestCode 文件上传回调对应码
* @param file 文件
* @param listener 监听回调
*/
public void uploadFile(int requestCode, UploadFileListener listener, File... file){
startUploadFile(requestCode,listener,file);
}
/**
* 上传文件
*
* @param requestCode 文件上传回调对应码
* @param files 文件
* @param listener 监听回调
*/
private void startUploadFile(int requestCode, UploadFileListener listener, File... files){
if(!isUploading) {
isUploading = true;
}else{
if(listener != null){
listener.uploadFailed("当前正在执行上传任务",requestCode);
}
return;
}
if(executorService.isShutdown()){//线程池被关闭,创建新的线程池
executorService = Executors.newSingleThreadExecutor();
}
BaseActivity.getCurrentActivity().showLoadingDialog("正在上传");
long time = new Date().getTime();
if(token == null || token.time<time){//判断token 及是否失效
//此处为 网络请求后台获取 七牛token信息,可根据当前项目的接口请求框架修改
/* 返回参数 主要用到 "time=" + time +
"token=" + token +
"domain=" + domain +*/
RetrofitUtils.instance()//获取七牛token
.getRequest()
.getQiniuToken()
.compose(RxJavaUtils.applySchedulers())
.subscribe(new HttpCallBack<QiniuToken>() {
@Override
public void onSuccess(QiniuToken result) {
if(result.code == HttpResultCode.SUCCESS){//获取token成功
token = result.map;
uploadFileQiNiu(requestCode, listener, token, files);
}else{
BaseActivity.getCurrentActivity().closeLoadingDialog();
if(listener != null){
listener.uploadFailed(result.msg,requestCode);
}
}
}
@Override
public void onFailure(Throwable e) {
BaseActivity.getCurrentActivity().closeLoadingDialog();
if(listener != null){
listener.uploadFailed(e.getMessage(),requestCode);
}
}
});
}else {
uploadFileQiNiu(requestCode, listener, token, files);
}
}
/**
* 路径转换为文件
* @param filePath
* @return
*/
private File[] getFileByPath(String... filePath){
File[] file = new File[filePath.length];
for(int i = 0 ; i < filePath.length ; i ++){
file[i] = new File(filePath[i]);
}
return file;
}
ExecutorService executorService = Executors.newSingleThreadExecutor();//线程池服务
Semaphore semaphore = new Semaphore(1,false);
/**
* 上传文件,指定请求号
*
* @param requestCode 请求号
* @param files 本地文件
* @param listener 监听回调
*/
private void uploadFileQiNiu(int requestCode, UploadFileListener listener, QiniuToken.Map token, File... files){
List<String> fielUrls = new ArrayList<>();
for(int i = 0 ; i < files.length ; i ++){
final int index = i;
Thread thread = new Thread() {
@Override
public void run() {
try {
Log.e("uploadFile","uploadFileQiNiu start "+index );
semaphore.acquire();
uploadFileQiniu(files[index],token,new UpQiniuListener() {
@Override
public void uploadSuccess(String url) {
Log.e("uploadFile","uploadFileQiNiu end "+index);
fielUrls.add(url);
if(fielUrls.size() == files.length && isUploading) {
BaseActivity.getCurrentActivity().closeLoadingDialog();
Log.i("qiniu", "Upload Success"); //正确的:{"hash":"Ft-886ksoUqzTBhiUewWITF_mcnB","key":"14e357c7239b439188065d507b25bd1f.amr"}
if(listener != null){
listener.uploadSuccess(fielUrls.size()==1?fielUrls.get(0):new Gson().toJson(fielUrls),requestCode);
}
isUploading = false;
}
semaphore.release();
}
@Override
public void uploadFailed(String err) {
BaseActivity.getCurrentActivity().closeLoadingDialog();
Log.i("qiniu", "Upload Fail");
//如果失败,这里可以把info信息上报自己的服务器,便于后面分析上传错误原因
if(listener != null){
listener.uploadFailed(err,requestCode);
}
isUploading = false;
semaphore.release();
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
executorService.submit(thread);
}
executorService.shutdown();
}
/**
* 上传文件,指定请求号
*
* @param file 本地文件
* @param listener 监听回调
*/
private void uploadFileQiniu(File file, QiniuToken.Map token,UpQiniuListener listener){
String name = file.getName();
DateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
String filename = "network/"+simpleDateFormat.format(new Date())+"/"+UUID.randomUUID().toString().replace("-", "") + name.substring(name.lastIndexOf("."));
uploadManager.put(file
, filename, token.token
, new UpCompletionHandler() {
@Override
public void complete(String key, ResponseInfo info, JSONObject response) { //response ={"error":"incorrect region, please use up-z2.qiniup.com"}
//res包含hash、key等信息,具体字段取决于上传策略的设置 回调中key:36d5895cba64403faf8b3ef8ea7c8cb0.amr
Log.i("qiniu", "Upload info"+info);
//删除压缩文件
File directory = new File(STOREPATH);
if(directory != null && directory.listFiles() != null && directory.listFiles().length != 0){
for(File temp :directory.listFiles()){
if(temp != null){
temp.delete();//删除临时文件
}
}
}
if (info.isOK()) {
listener.uploadSuccess(token.domain.lastIndexOf("/")==token.domain.length()-1 ? token.domain:token.domain+"/"+key);
//http://q349xx31l.bkt.clouddn.com/14e357c7239b439188065d507b25bd1f.amr
} else {
//如果失败,这里可以把info信息上报自己的服务器,便于后面分析上传错误原因
listener.uploadFailed(info.error);
}
}
},null);
}
public interface UpQiniuListener{
void uploadSuccess(String url);
void uploadFailed(String msg);
}
public interface UploadFileListener{
void uploadSuccess(String url,int uploadRequestCode);
void uploadFailed(String message,int requestCode);
}
}
也可以加QQ群交流技术
最后推荐一个我自己写的MVVM开源项目《Open MVVM》
(想加扣扣讨论群请进入文章结尾查看群号)
有问题请私信,留言,或者发送邮件到我扣扣邮箱 qingingrunt2010