BCSUtils备份

public class BCSUtil {

	private static String hostBcs = "bcs.duapp.com";
	private static String accessKeyBcs = "";
	private static String secretKeyBcs = "";
	private static String bucketBcs = "dreamfactory";
	private static String baseContentBcs = "MBO" + "\n" + "Method=GET" + "\n"
			+ "Bucket=dreamfactory" + "\n" + "Object=";
	private BaiduBCS baiduBCS;

	private static BCSUtil instance;

	public static BCSUtil getInstance() {
		if (instance == null) {
			instance = new BCSUtil();
		}
		return instance;
	}

	private BCSUtil() {
		BCSCredentials credentials = new BCSCredentials(accessKeyBcs,
				secretKeyBcs);
		baiduBCS = new BaiduBCS(credentials, hostBcs);
		baiduBCS.setDefaultEncoding("UTF-8"); // Default UTF-8
	}

	public String putAvatarObject(String avatar64, int uid) {
		String objectName = getAvatarObjectName(uid);
		byte[] avatarBytes = Base64.decodeBase64(avatar64);
		ByteArrayInputStream inputStream = new ByteArrayInputStream(avatarBytes);
		ObjectMetadata metadata = new ObjectMetadata();
		metadata.setContentType("image/*");
		metadata.setContentLength(avatarBytes.length);
		
		try {
			PutObjectRequest request = new PutObjectRequest(bucketBcs,
					objectName, inputStream, metadata);
			BaiduBCSResponse<ObjectMetadata> response = baiduBCS
					.putObject(request);

			System.out.println("success!!   x-bs-request-id: "
					+ response.getRequestId());
			return getAvatarUrl(uid, objectName);
		} catch (Exception e) {
			System.out.println("faild!!");
			return null;
		}

	}

	private String getAvatarObjectName(int uid) {
		long time = System.currentTimeMillis();
		return "/avatar/user" + uid + "_" + time +".png";
	}

	private String getAvatarUrl(int uid, String objectName) {
		try {
			String signatureString = getSignature(objectName);
			String signString = "MBO:" + accessKeyBcs + ":" + signatureString;
			String urlString = "http://bcs.duapp.com/dreamfactory" + objectName
					+ "?sign=" + signString;
			return urlString;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	private String getSignature(String objectName)
			throws GeneralSecurityException, UnsupportedEncodingException {
		String contentBcs = baseContentBcs + objectName + "\n";
		SecretKey secretKey = null;
		byte[] keyBytes = secretKeyBcs.getBytes();
		secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");
		Mac mac = Mac.getInstance("HmacSHA1");
		mac.init(secretKey);
		byte[] text = contentBcs.getBytes();
		String base64Signature = new String(Base64.encodeBase64(mac
				.doFinal(text))).trim();
		// URLEncoder.encode(base64Signature);
		return base64Signature;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值