首先登录阿里云账号
到控制台里选择对象存储OSS,开通oss,注意此服务会根据流量收取费用
点击Access Key按要求创建进行,
记下AccessKey 和Accesssecret
在项目里添加阿里云的依赖
com.aliyun.oss
aliyun-sdk-oss
2.4.0
commons-fileupload
commons-fileupload
1.3.1
application.yml详细的配置文件
oos:
endpoint: oss-cn-shanghai.aliyuncs.com
keyid: xxxxxxxx # 填写刚刚生成的AccessKey
keysecret: xxxxxxx # 填写刚刚生成的Accesssecret
bucketname: 2019131 # bucket名称
filehost: 11111 #bucket下文件夹的路径
endpoint是根据你新建申请bucket地域选择的,点击+号
新建完bucket点击你的bucket、
外网访问里找到endpoint
下面是详细代码
获取application.yml配置的ConstantProperties类
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "oos")
public class ConstantProperties {
private String endpoint;
private String keyid;
private String keysecret;
private String bucketname;
private String filehost;
}
上传,获取文件列表,删除的util类
@Service
@Slf4j
public class AliyunOSSUtil {
@Autowired
private ConstantProperties constantProperties;
private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
/**
* 上传
* @param file
* @return
*/
public String upload(File file){
log.info("=========>OSS文件上传开始:"+file.getName());
String endpoint= constantProperties.getEndpoint();
String accessKeyId= constantProperties.getKeyid();
String accessKeySecret=constantProperties.getKeysecret();
String bucketName=constantProperties.getBucketname();
String fileHost=constantProperties.getFilehost();
System.out.println(endpoint+"endpoint");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = format.format(new Date());
if(null == file){
return null;
}
OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
try {
//容器不存在,就创建
if(! ossClient.doesBucketExist(bucketName)){
ossClient.createBucket(bucketName);
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
ossClient.createBucket(createBucketRequest);
}
//创建文件路径
String fileUrl = fileHost+"/"+(dateStr + "/" + UUID.randomUUID().toString().replace("-","")+"-"+file.getName());
//上传文件
PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
//设置权限 这里是公开读
ossClient.setBucketAcl(bucketName,CannedAccessControlList.PublicRead);
if(null != result){
log.info("==========>OSS文件上传成功,OSS地址:"+fileUrl);
return fileUrl;
}
}catch (OSSException oe){
log.error(oe.getMessage());
}catch (ClientException ce){
log.error(ce.getMessage());
}finally {
//关闭
ossClient.shutdown();
}
return null;
}
/**
* 删除
* @param fileKey
* @return
*/
public String deleteBlog(String fileKey){
log.info("=========>OSS文件删除开始");
String endpoint= constantProperties.getEndpoint();
String accessKeyId= constantProperties.getKeyid();
String accessKeySecret=constantProperties.getKeysecret();
String bucketName=constantProperties.getBucketname();
String fileHost=constantProperties.getFilehost();
try {
OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
if(!ossClient.doesBucketExist(bucketName)){
log.info("==============>您的Bucket不存在");
return "您的Bucket不存在";
}else {
log.info("==============>开始删除Object");
ossClient.deleteObject(bucketName,fileKey);
log.info("==============>Object删除成功:"+fileKey);
return "==============>Object删除成功:"+fileKey;
}
}catch (Exception ex){
log.info("删除Object失败",ex);
return "删除Object失败";
}
}
/**
* 查询文件名列表
* @param bucketName
* @return
*/
public List getObjectList(String bucketName){
List listRe = new ArrayList<>();
String endpoint= constantProperties.getEndpoint();
String accessKeyId= constantProperties.getKeyid();
String accessKeySecret=constantProperties.getKeysecret();
try {
log.info("===========>查询文件名列表");
OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
//列出11111目录下今天所有文件
listObjectsRequest.setPrefix("11111/"+format.format(new Date())+"/");
ObjectListing list = ossClient.listObjects(listObjectsRequest);
for(OSSObjectSummary objectSummary : list.getObjectSummaries()){
System.out.println(objectSummary.getKey());
listRe.add(objectSummary.getKey());
}
return listRe;
}catch (Exception ex){
log.info("==========>查询列表失败",ex);
return new ArrayList<>();
}
}
}
controller类
@Controller
@RequestMapping("/oss")
@Slf4j
public class UploadController {
@Autowired
private AliyunOSSUtil aliyunOSSUtil;
@Autowired
private ConstantProperties constantProperties;
@GetMapping("/toUploadBlog")
public String toUploadBlog(){
return "oss/upload";
}
@PostMapping("/toUploadBlog")
public String toUploadBlogPost(MultipartFile file){
log.info("=========>文件上传");
try {
if(null != file){
String filename = file.getOriginalFilename();
if(!"".equals(filename.trim())){
File newFile = new File(filename);
FileOutputStream os = new FileOutputStream(newFile);
os.write(file.getBytes());
os.close();
file.transferTo(newFile);
//上传到OSS
String uploadUrl = aliyunOSSUtil.upload(newFile);
}
}
}catch (Exception ex){
ex.printStackTrace();
}
return "oss/index";
}
@GetMapping("/getObjectList")
@ResponseBody
public List getObjectList(){
String bucketName=constantProperties.getBucketname();
System.out.println(bucketName);
List objectList = aliyunOSSUtil.getObjectList(bucketName);
return objectList;
}
@GetMapping("/delete")
@ResponseBody
public String deleteBlog(@RequestParam("key")String key){
aliyunOSSUtil.deleteBlog(key);
return "删除成功";
}
}
templates/oss下的html,这里我用了thymeleaf
index.html
文件上传
HELLO,THIS IS OSS
上传成功
upload.html
文件上传
http://localhost:8080/oss/toUploadBlog
选择文件上传
打开阿里云控制台,点击bucket->文件管理
在2019131下的11111文件夹下看到刚刚上传的图片
http://localhost:8080/oss/getObjectList
查看列表
http://localhost:8080/oss/delete?key=11111/2019-01-04/42d2377c2f904b1d80c905e4b3838db9-TIM%E6%88%AA%E5%9B%BE20190104164115.png
删除11111/2019-01-04/42d2377c2f904b1d80c905e4b3838db9-TIM%E6%88%AA%E5%9B%BE20190104164115.png