1.accessKeyId 与 accessKeySecret 是由系统分配给用户的,称为ID对,用于标识用户,为访问OSS做签名验证。
2.Bucket是OSS上的命名空间,相当于数据的容器,可以存储若干数据实体(Object)
你可以按照下面的代码新建一个Bucket:
/// <summary>
/// 新建存储对象容器Bucket
/// </summary>
/// <param name="bucketName">容器名称</param>
void CreateBucket(string bucketName)
{
//初始化 OSSClient
OssClient ossClient = new OssClient(endPoint, accessKeyId, accessKeySecret);
// 新建一个Bucket
var bucket = ossClient.CreateBucket(bucketName);
Console.WriteLine(bucket.CreationDate);
}
由于Bucket的名字是全局唯一的,所以尽量保证你的 bucketName 不与别人重复。
其实也可以在阿里云的OSS管理控制台创建。
public class OssUtils {
private static String endpoint = "";
private static String accessKeyId = "";
private static String accessKeySecret = "";
private static String bucketName = "";
/**
* oss 下载文件
*
* @param ossKey
* @return
*/
public static File downLoadFile(String ossKey) throws Exception {
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
try {
// 判断Bucket是否存在。详细请参看“SDK手册 > Java-SDK > 管理Bucket”。
if (ossClient.doesBucketExist(bucketName)) {
// 先将文件写入临时文件再下载
String filename = "temp" + ossKey.substring(ossKey.lastIndexOf("."), ossKey.length());
File f = new File(filename);
ossClient.getObject(new GetObjectRequest(bucketName, ossKey), f);
return f;
}
return null;
} catch (Exception e) {
throw e;
} finally {
ossClient.shutdown();
}
}
/**
* 上传文件到OSS
*
* @param ossKey
* @param f
* @throws Exception
*/
public static void uploadFIle(String ossKey, File f) throws Exception {
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
try {
// 判断Bucket是否存在。详细请参看“SDK手册 > Java-SDK > 管理Bucket”。
if (ossClient.doesBucketExist(bucketName)) {
ObjectMetadata meta = new ObjectMetadata();
// 设置自定义元信息name的值为my-data
meta.addUserMetadata("Content-Type", "application/octet-stream");
meta.addUserMetadata("Content-Disposition", "attachment;filename=" + ossKey);
InputStream inputStream = new FileInputStream(f);
// 上传
ossClient.putObject(bucketName, ossKey, inputStream);
inputStream.close();
// 转换pdf文件
// ChangeFile(f, ossKey);
}
} catch (Exception e) {
throw e;
} finally {
ossClient.shutdown();
}
}
}