百度云和阿里云类似,本文以百度云为例。
创建百度云对象存储实例
1. 进入百度云官网找到对象存储BOS
2.创建Bucket
3.客户端认证信息
accessKeyId和accessKeySecret数据
配置BOS和OSS的配置文件:
accessKeyId和accessKeySecret为上图中认证信息中的数据。
endpoint为bucket中的官方域名。
test:
file:
bos:
accessKeyId: idTest
accessKeySecret: secretTest
endpoint: endPointTest
oss:
accessKeyId: idTest
accessKeySecret: secretTest
endpoint: endPointTest
bucket: test-dev
filePath: /template/dev
imagePath: /mnt/test-cloud/images
创建文件的客户端
1. 百度云客户端
public class DefaultBOSClient implements InitializingBean {
@Value("${test.file.bos.endpoint}")
private String endpoint;
@Value("${test.file.bos.accessKeyId}")
private String accessKeyId;
@Value("${test.file.bos.accessKeySecret}")
private String accessKeySecret;
private BosClient client = null;
public BosClient getDefaultBOSClient() {
if (client == null) {
BosClientConfiguration defalutClientConfig = DefaultBOSClientConfiguration.getDefalutClientConfig();
defalutClientConfig.setCredentials(new DefaultBceCredentials(accessKeyId, accessKeySecret));
defalutClientConfig.setEndpoint(endpoint);
defalutClientConfig.setProtocol(Protocol.HTTPS);
client = new BosClient(defalutClientConfig);
}
return client;
}
public void shutdownOSSClient() {
}
@Override
public void afterPropertiesSet() throws Exception {
BosClientConfiguration defalutClientConfig = DefaultBOSClientConfiguration.getDefalutClientConfig();
defalutClientConfig.setCredentials(new DefaultBceCredentials(accessKeyId, accessKeySecret));
defalutClientConfig.setEndpoint(endpoint);
defalutClientConfig.setProtocol(Protocol.HTTPS);
client = new BosClient(defalutClientConfig);
}
}
2. 阿里云客户端
public class DefaultOSSClient implements InitializingBean {
@Value("${test.file.oss.endpoint}")
private String endpoint;
@Value("${test.file.oss.accessKeyId}")
private String accessKeyId;
@Value("${test.file.oss.accessKeySecret}")
private String accessKeySecret;
private OSSClient client = null;
public OSSClient getDefaultOSSClient() {
if (client == null) {
client = new OSSClient(endpoint, accessKeyId, accessKeySecret, DefaultOSSClientConfiguration.getDefalutClientConfig());
}
return client;
}
public void shutdownOSSClient() {
/*if(client!=null) {
client.shutdown();
client = null;
}*/
}
@Override
public void afterPropertiesSet() throws Exception {
client = new OSSClient(endpoint, accessKeyId, accessKeySecret, DefaultOSSClientConfiguration.getDefalutClientConfig());
}
通过文件名和桶名获取文件的URL
阿里云和百度云的操作API类似,以百度云为例:
public String getPermissions(String bucketName, String objectName) {
BosClient bosClient = defaultBOSClient.getDefaultBOSClient();
boolean found = bosClient.doesObjectExist(bucketName, objectName);
if (!found) {
throw new CommonException("file.not.found");
}
// 设置URL过期时间为1小时。
Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
int expirationSecond = 3600 * 1000;
// 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
URL url = bosClient.generatePresignedUrl(bucketName, objectName, expirationSecond);
String urlStr = url.toString();
defaultBOSClient.shutdownOSSClient();
urlStr=urlStr.replace("http://","https://");
return urlStr;
}
文件下载
public File download(String objectName, String bucketName) {
File localFile = new File(path + objectName);
BosClient defaultBOSClient = this.defaultBOSClient.getDefaultBOSClient();
boolean found = defaultBOSClient.doesObjectExist(bucketName, objectName);
if (!found) {
throw new CommonException("file.not.found");
}
defaultBOSClient.getObject(new GetObjectRequest(bucketName, objectName), localFile);
this.defaultBOSClient.shutdownOSSClient();
return localFile;
}
删除文件
public boolean delete(String bucketName, String objectName) {
boolean found = true;
try {
BosClient bosClient = defaultBOSClient.getDefaultBOSClient();
found = bosClient.doesObjectExist(bucketName, objectName);
if (!found) {
throw new CommonException("file.not.found");
}
bosClient.deleteObject(bucketName, objectName);
defaultBOSClient.shutdownOSSClient();
} catch (Exception e) {
found = false;
}
return found;
}
文件上传
简单的上传, 以数据流形式上传Object(不超过5GB)。上传大文件可以使用分块上传。(目前正在研究分块上传这个功能)
public String uploadAttachment(String bucketName, String originalFileName, String fileName, String fileType, InputStream stream) {
String url = null;
StringBuilder finalDispositionName = new StringBuilder();
try {
BosClient bosClient = defaultBOSClient.getDefaultBOSClient();
// 初始化上传输入流 (设置上传文件时自定义Object的Http Header)
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(stream.available());
//meta 元信息
metadata.setContentType(getContentType(fileType));
if(!VIDEO_MP4.equals(metadata.getContentType())){
finalDispositionName.append("\"").append(originalFileName).append("\"");
originalFileName = finalDispositionName.toString();
metadata.setContentDisposition("attachment;filename=" + new String(originalFileName.getBytes("GB2312"), "ISO_8859_1"));
}
bosClient.putObject(bucketName, fileName, stream, metadata);
url = bosClient.getEndpoint().toString().replaceFirst("http://", "https://" + bucketName + ".") + "/" + fileName;
defaultBOSClient.shutdownOSSClient();
} catch (IOException e) {
e.printStackTrace();
}
return url;
}
default String getContentType(String fileType) {
//文件名后缀
if (".bmp".equalsIgnoreCase(fileType)) {
return "image/bmp";
}
if (".gif".equalsIgnoreCase(fileType)) {
return "image/gif";
}
if (".jpeg".equalsIgnoreCase(fileType) || ".jpg".equalsIgnoreCase(fileType) || ".png".equalsIgnoreCase(fileType)) {
return "image/jpeg";
}
if (".html".equalsIgnoreCase(fileType)) {
return "text/html";
}
if (".txt".equalsIgnoreCase(fileType)) {
return "text/plain";
}
if (".vsd".equalsIgnoreCase(fileType)) {
return "application/vnd.visio";
}
if (".ppt".equalsIgnoreCase(fileType) || "pptx".equalsIgnoreCase(fileType)) {
return "application/vnd.ms-powerpoint";
}
if (".doc".equalsIgnoreCase(fileType) || "docx".equalsIgnoreCase(fileType)) {
return "application/msword";
}
if (".xml".equalsIgnoreCase(fileType)) {
return "text/xml";
}
if (".pdf".equalsIgnoreCase(fileType)) {
return "application/pdf";
}
if (".xls".equalsIgnoreCase(fileType)) {
return "application/vnd.ms-excel";
}
if (".xsd".equalsIgnoreCase(fileType)) {
return "text/xml";
}
String[] voice = {".avi", ".mov", ".rmvb", ".rm", ".flv", ".mp4", ".3gp",".wmv"};
if (Arrays.asList(voice).contains(fileType)) {
return "video/mp4";
}
return "application/octet-stream";
}