配置文件:
oss.host=http://oss-cn-shanghai.aliyuncs.com
oss.accessid=xxx
oss.accesskey=xxx
oss.bucket=have-test
oss.dir=show
废话少说,直接上代码:
private IOssService iOssService;
@Value("${oss.dir}")
private String ossFileDir;
private String uploadFileToOss(MultipartFile file){
String fileUrl = "";
try{
byte[] bytes = file.getBytes();
String dataName = file.getOriginalFilename();
String fileName = ossFileDir + "/" + dataName;
fileUrl = iOssService.uploadFile(fileName,file.getContentType(), bytes);
logger.info("uploadFile : ossFileUrl : {}", fileUrl);
} catch (IOException e) {
e.printStackTrace();
}
return fileUrl;
}
package com.wps.education.common.oss;
public interface IOssService {
public boolean createFolder(String folderName);
public String uploadFile(String key, String contentType, byte[] bytes);
public String getPictureUri(String key);
public boolean deleteFile(String key);
public void clearBucket();
}
package com.wps.education.common.oss.Impl;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import javax.annotation.Resource;
import com.wps.education.common.oss.IOssDao;
import com.wps.education.common.oss.IOssService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.ServiceException;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
@Service
public class OssServiceImpl implements IOssService {
private static final Logger LOGGER = LoggerFactory.getLogger(OssServiceImpl.class);
@Value("${oss.host}")
private String host;//static String host = "http://oss-cn-beijing.aliyuncs.com";
@Value("${oss.accessid}")
private String accessid;//static String accessid = "Tk9bWYtSlxy3QFbJ";
@Value("${oss.accesskey}")
private String accesskey;//static String accesskey = "esTS8FVcwgWamJ7BctT2ZThZOPi4Rv";
@Value("${oss.bucket}")
private String bucket;//static String bucket = "cooserver";
@Resource
private IOssDao IOssDao;
@Override
public boolean createFolder(String folderName) {
LOGGER.debug("CreateFolder: creating folder " + folderName);
boolean created = false;
OSSClient client = new OSSClient(host, accessid, accesskey);
try {
if (IOssDao.findObject(client, bucket, folderName) == null) {
IOssDao.createFolder(client, bucket, folderName);
}
created = true;
} catch (ServiceException e) {
System.out.println(e.getErrorCode() + ":" + e.getErrorMessage());
e.printStackTrace();
} catch (ClientException e) {
System.out.println(e.getErrorCode() + ":" + e.getErrorMessage());
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return created;
}
@Override
public String uploadFile(String key, String contentType, byte[] bytes) {
LOGGER.debug("UploadPicture: uploading file " + key);
String uri = null;
OSSClient client = new OSSClient(host, accessid, accesskey);
InputStream input = new ByteArrayInputStream(bytes);
IOssDao.uploadFile(client, bucket, key, contentType, bytes.length, input);
uri = IOssDao.getObjectUri(client, bucket, key);
input = null;
return uri;
}
@Override
public String getPictureUri(String key) {
LOGGER.debug("GetPictureUri: key " + key);
String uri = null;
OSSClient client = new OSSClient(host, accessid, accesskey);
try {
uri = IOssDao.getObjectUri(client, bucket, key);
} catch (ServiceException e) {
System.out.println(e.getErrorCode() + ":" + e.getErrorMessage());
e.printStackTrace();
} catch (ClientException e) {
System.out.println(e.getErrorCode() + ":" + e.getErrorMessage());
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return uri;
}
@Override
public boolean deleteFile(String key) {
LOGGER.debug("DeleteFile: deleting file " + key);
OSSClient client = new OSSClient(host, accessid, accesskey);
boolean deleted = false;
try {
deleted = IOssDao.deleteObject(client, bucket, key);
} catch (ServiceException e) {
System.out.println(e.getErrorCode() + ":" + e.getErrorMessage());
e.printStackTrace();
} catch (ClientException e) {
System.out.println(e.getErrorCode() + ":" + e.getErrorMessage());
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return deleted;
}
@Override
public void clearBucket() {
LOGGER.debug("clearFolder");
ObjectListing listObject = null;
boolean haveObject = false;
boolean havePrefix = false;
do {
OSSClient client = new OSSClient(host, accessid, accesskey);
try {
listObject = IOssDao.listObject(client, bucket, "1");
// 遍历所有Object
System.out.println("Objects:");
List
if ((listObjectSumary != null) && (listObjectSumary.size() > 0)) {
haveObject = true;
for (OSSObjectSummary objectSummary : listObjectSumary) {
String key = objectSummary.getKey();
System.out.println(key);
client.deleteObject(bucket, key);
}
} else {
haveObject = false;
}
// 遍历所有CommonPrefix
System.out.println("\nCommonPrefixs:");
List
if ((listCommonPrefix != null) && (listCommonPrefix.size() > 0)) {
havePrefix = true;
for (String commonPrefix : listCommonPrefix) {
System.out.println(commonPrefix);
}
} else {
havePrefix = false;
}
} catch (ServiceException e) {
System.out.println(e.getErrorCode() + ":" + e.getErrorMessage());
e.printStackTrace();
} catch (ClientException e) {
System.out.println(e.getErrorCode() + ":" + e.getErrorMessage());
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
client = null;
} while (haveObject || havePrefix);
}
}
package com.wps.education.common.oss;
import java.io.IOException;
import java.io.InputStream;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectListing;
public interface IOssDao {
public void ensureBucket(OSSClient client, String bucketName) throws OSSException, ClientException;
public OSSObject findObject(OSSClient client, String bucketName, String key) throws OSSException, ClientException;
public void createFolder(OSSClient client, String bucketName, String folderName) throws IOException;
public void uploadFile(OSSClient client, String bucketName, String key, String contentType, long contentLength, InputStream input) throws OSSException, ClientException;
public String getObjectUri(OSSClient client, String bucketName, String key) throws ClientException;
public boolean deleteObject(OSSClient client, String bucketName, String key) throws OSSException, ClientException;
public ObjectListing listObject(OSSClient client, String bucketName, String folderName) throws OSSException, ClientException;
}
package com.wps.education.common.oss.Impl;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import com.wps.education.common.oss.IOssDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSErrorCode;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.ServiceException;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
@Repository
public class OssDaoImpl implements IOssDao {
private static final Logger LOGGER = LoggerFactory.getLogger(OssDaoImpl.class);
// 创建Bucket.
@Override
public void ensureBucket(OSSClient client, String bucketName) throws OSSException, ClientException {
try {
// 创建bucket
client.createBucket(bucketName);
} catch (ServiceException e) {
if (!OSSErrorCode.BUCKET_ALREADY_EXISTS.equals(e.getErrorCode())) {
// 如果Bucket已经存在,则忽略
throw e;
}
}
}
@Override
public OSSObject findObject(OSSClient client, String bucketName, String key) throws OSSException, ClientException {
OSSObject object = null;
try {
object = client.getObject(bucketName, key);
} catch (ServiceException e) {
if (!OSSErrorCode.NO_SUCH_KEY.equals(e.getErrorCode())) {
// 非key未找到异常,需要被调用者处理
throw e;
}
}
return object;
}
@Override
public void createFolder(OSSClient client, String bucketName, String folderName) throws IOException {
LOGGER.debug("CreateFolder: creating folder " + folderName + " in bucket " + bucketName);
//要创建的文件夹名称,在满足Object命名规则的情况下以"/"结尾
if (!folderName.endsWith("/")) {
folderName += "/";
}
ObjectMetadata objectMeta = new ObjectMetadata();
/*这里的size为0,注意OSS本身没有文件夹的概念,这里创建的文件夹本质上是一个size为0的Object,dataStream仍然可以有数据
*照样可以上传下载,只是控制台会对以"/"结尾的Object以文件夹的方式展示,用户可以利用这种方式来实现
*文件夹模拟功能,创建形式上的文件夹
*/
byte[] buffer = new byte[0];
ByteArrayInputStream in = new ByteArrayInputStream(buffer);
objectMeta.setContentLength(0);
try {
client.putObject(bucketName, folderName, in, objectMeta);
} finally {
in.close();
}
}
// 把Bucket设置为所有人可读
// private static void setBucketPublicReadable(OSSClient client, String bucketName) throws OSSException, ClientException {
// //创建bucket
// client.createBucket(bucketName);
//
// //设置bucket的访问权限,public-read-write权限
// client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
// }
// 上传文件
@Override
public void uploadFile(OSSClient client, String bucketName, String key, String contentType, long contentLength, InputStream input) throws OSSException, ClientException {
ObjectMetadata objectMeta = new ObjectMetadata();
objectMeta.setContentLength(contentLength);
// 可以在metadata中标记文件类型
objectMeta.setContentType(contentType);//"image/jpeg"
client.putObject(bucketName, key, input, objectMeta);
}
@Override
public String getObjectUri(OSSClient client, String bucketName, String key) throws ClientException {
Date date = new Date();
date.setTime(date.getTime() + (31 * 24 * 3600 * 1000)); // url链接保留一周
URL url = client.generatePresignedUrl(bucketName, key, date);
String uri = null;
if (url != null) {
uri = url.toString();
uri = uri.substring(0, uri.indexOf('?', 0));
}
return uri;
}
@Override
public boolean deleteObject(OSSClient client, String bucketName, String key) throws OSSException, ClientException {
if (findObject(client, bucketName, key) != null) {
client.deleteObject(bucketName, key);
return true;
} else {
return false;
}
}
@Override
public ObjectListing listObject(OSSClient client, String bucketName, String folderName) throws OSSException, ClientException {
// 构造ListObjectsRequest请求
ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
// "/" 为文件夹的分隔符
listObjectsRequest.setDelimiter("/");
if ((folderName != null) && (!folderName.isEmpty())) {
// 列出fun目录下的所有文件和文件夹
listObjectsRequest.setPrefix(folderName + "/");
}
return client.listObjects(listObjectsRequest);
}
}