package com.qiniu.ui.utils;
import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.os.Environment; import android.util.Log; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.qiniu.android.storage.UpProgressHandler; import com.qiniu.android.storage.UploadManager; import com.qiniu.android.storage.UploadOptions; import com.qiniu.android.utils.UrlSafeBase64; import com.qiniu.api.auth.AuthException; import com.qiniu.api.auth.digest.Mac; import com.qiniu.api.rs.PutPolicy; import com.qiniu.ui.SHA; import com.qiniu.ui.contains.QiNiuConfig; import org.apache.http.Header; import org.json.JSONException; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.util.Random; import static com.qiniu.ui.SHA.hMacSHA1Encrypt;
public class QiniuUitls {
private static final String fileName = "temp.jpg"; private static final String tempJpeg = Environment.getExternalStorageDirectory().getPath() + "/" + fileName;
private static int maxWidth = 720; private static int maxHeight = 1080;
public interface QiniuUploadUitlsListener { void onSucess(String fileUrl); void onError(int errorCode, String msg); void onProgress(int progress); }
public interface QiniuRequestListener { void onSucceed(byte[] bytes); void onFailed(byte[] bytes); }
public static boolean saveBitmapToJpegFile(Bitmap bitmap, String filePath, int quality) { try { FileOutputStream fileOutStr = new FileOutputStream(filePath); BufferedOutputStream bufOutStr = new BufferedOutputStream(fileOutStr); resizeBitmap(bitmap).compress(CompressFormat.JPEG, quality, bufOutStr); bufOutStr.flush(); bufOutStr.close(); } catch (Exception exception) { return false; } return true; }
public static Bitmap resizeBitmap(Bitmap bitmap) { if (bitmap != null) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); if (width > maxWidth) { int pWidth = maxWidth; int pHeight = maxWidth * height / width; Bitmap result = Bitmap.createScaledBitmap(bitmap, pWidth, pHeight, false); bitmap.recycle(); return result; } if (height > maxHeight) { int pHeight = maxHeight; int pWidth = maxHeight * width / height; Bitmap result = Bitmap.createScaledBitmap(bitmap, pWidth, pHeight, false); bitmap.recycle(); return result; } } return bitmap; }
public static void uploadImage(Bitmap bitmap, QiniuUploadUitlsListener listener) { saveBitmapToJpegFile(bitmap, tempJpeg,100); uploadImage(tempJpeg, listener); }
public static void uploadImage(String filePath, final QiniuUploadUitlsListener listener) { final String fileUrlUUID = getFileUrlUUID(); String token = getToken(); if (token == null) { if (listener != null) { listener.onError(-1, "token is null"); } return; } UploadManager uploadManager = new UploadManager(); uploadManager.put(filePath, fileUrlUUID, token, (key, info, response) -> { System.out.println("debug:info = " + info + ",response = " + response); if (info != null && info.statusCode == 200) { String fileRealUrl = getRealUrl(fileUrlUUID); System.out.println("debug:fileRealUrl = " + fileRealUrl); if (listener != null) { listener.onSucess(fileRealUrl); } } else { if (listener != null) { listener.onError(info.statusCode, info.error); } } }, new UploadOptions(null, null, false, new UpProgressHandler() { public void progress(String key, double percent) { if (listener != null) { listener.onProgress((int) (percent * 100)); } } }, null)); }
private static String getFileUrlUUID() { String filePath = android.os.Build.MODEL + "__" + System.currentTimeMillis() + "__" + (new Random().nextInt(500000)) + "_" + (new Random().nextInt(10000)); return filePath.replace(".", "0"); }
private static String getRealUrl(String fileUrlUUID) { String filePath = "http://" + QiNiuConfig.QINIU_BUCKNAME + ".qiniudn.com/" + fileUrlUUID; return filePath; }
private static String getToken() { Mac mac = new Mac(QiNiuConfig.QINIU_AK, QiNiuConfig.QINIU_SK); PutPolicy putPolicy = new PutPolicy(QiNiuConfig.QINIU_BUCKNAME); putPolicy.returnBody = "{\"name\": $(fname),\"size\": \"$(fsize)\",\"w\": \"$(imageInfo.width)\",\"h\": \"$(imageInfo.height)\",\"key\":$(etag)}"; try { String uptoken = putPolicy.token(mac); System.out.println("debug:uptoken = " + uptoken); return uptoken; } catch (AuthException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return null; }
public static String downloadFile(String domain,String imgKey){
StringBuilder sb =new StringBuilder(); String url = sb.append(domain).append(imgKey).append("?e=1478365261").toString(); Log.e("encodedEntryURI",url);
byte[] sign =null; try { sign = SHA.hMacSHA1Encrypt(url,QiNiuConfig.QINIU_SK); } catch (Exception e) { e.printStackTrace(); } String encodedSign = UrlSafeBase64.encodeToString(sign); sb.append("&token=").append(QiNiuConfig.QINIU_AK).append(":").append(encodedSign); Log.e("download token",sb.toString()); return sb.toString(); }
public static void listFile(String bucket, String prefix,final QiniuRequestListener listener){
try{ StringBuilder sb = new StringBuilder();
String entryUrl = sb.append("bucket=").append(bucket) .append("&prefix=").append(prefix).toString(); String host = "http://rsf.qbox.me"; String path = "/list?" +entryUrl; String url = host+path; Log.e("AAAAAAA", url); byte[] sign = SHA.hMacSHA1Encrypt(path+"\n", QiNiuConfig.QINIU_SK); String encodedSign = UrlSafeBase64.encodeToString(sign); String authorization = QiNiuConfig.QINIU_AK + ':' + encodedSign; AsyncHttpClient client = new AsyncHttpClient(); client.addHeader("Content-Type","application/x-www-form-urlencoded"); client.addHeader("Authorization", "QBox "+authorization); RequestParams params = new RequestParams(); client.post(url, params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int i, Header[] headers, byte[] bytes) { if (null!=listener) listener.onSucceed(bytes); }
@Override public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) { if (null!=listener) listener.onFailed(bytes); } }); }catch(Exception e){ e.printStackTrace(); } return ; }
public static boolean deleteFile(String bucket,String fileName,final QiniuRequestListener listener){ try{ String entryUrl = bucket+":"+fileName; String encodedEntryURI = UrlSafeBase64.encodeToString(entryUrl.getBytes()); String host = "http://rs.qiniu.com"; String path = "/delete/"+encodedEntryURI; String url = host+path; Log.e("AAAAAAA", url); byte[] sign = hMacSHA1Encrypt(path+"\n", QiNiuConfig.QINIU_SK); String encodedSign = UrlSafeBase64.encodeToString(sign); String authorization = QiNiuConfig.QINIU_AK + ':' + encodedSign;
AsyncHttpClient client = new AsyncHttpClient(); client.addHeader("Content-Type","application/x-www-form-urlencoded"); client.addHeader("Authorization", "QBox "+authorization); RequestParams params = new RequestParams(); client.post(url, params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int i, Header[] headers, byte[] bytes) { if (null!=listener) listener.onSucceed(bytes); }
@Override public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) { if (null!=listener) listener.onFailed(bytes); if (null!=bytes) { String s = new String(bytes); } } });
}catch(Exception e){ e.printStackTrace(); } return false; }
}
|