1、引入依赖
<!-- aliyun oss -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.13.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
2、添加配置
#阿里云 OSS
#不同的服务器,地址不同
aliyun:
oss:
file:
endpoint: oss-accelerate.aliyuncs.com
keyid: ****************
keysecret: *******************
bucketname: qingb
filehost: qingbfolder
3、读取配置类
package com.bt.usercenter.oss.utils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
@Component
public class ConstantPropertiesUtils implements InitializingBean {
//读取配置文件内容
@Value("${aliyun.oss.file.endpoint}")
private String endpoint;
@Value("${aliyun.oss.file.keyid}")
private String keyId;
@Value("${aliyun.oss.file.keysecret}")
private String keySecret;
@Value("${aliyun.oss.file.bucketname}")
private String bucketName;
@Value("${aliyun.oss.file.filehost}")
private String fileHost;
//定义公开静态常量
public static String END_POIND;
public static String ACCESS_KEY_ID;
public static String ACCESS_KEY_SECRET;
public static String BUCKET_NAME;
public static String FILE_HOST;
@Override
public void afterPropertiesSet() throws Exception {
END_POIND = endpoint;
ACCESS_KEY_ID = keyId;
ACCESS_KEY_SECRET = keySecret;
BUCKET_NAME = bucketName;
FILE_HOST = fileHost;
}
}
4、工具类
package com.bt.usercenter.oss.utils;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
public class AliyunOSSUtil {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);
public static String upload(File file){
logger.info("=========>OSS文件上传开始:"+file.getName());
String endpoint=ConstantPropertiesUtils.END_POIND;
String accessKeyId=ConstantPropertiesUtils.ACCESS_KEY_ID;
String accessKeySecret=ConstantPropertiesUtils.ACCESS_KEY_SECRET;
String bucketName=ConstantPropertiesUtils.BUCKET_NAME;
String fileHost=ConstantPropertiesUtils.FILE_HOST;
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){
logger.info("==========>OSS文件上传成功,OSS地址:"+fileUrl);
return fileUrl;
}
}catch (OSSException oe){
logger.error(oe.getMessage());
}catch (ClientException ce){
logger.error(ce.getMessage());
}finally {
//关闭
ossClient.shutdown();
}
return null;
}
}
5、Controller
package com.bt.usercenter.controller.user;
import com.bt.usercenter.oss.utils.AliyunOSSUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
@Controller
@RequestMapping("upload")
public class UploadController {
private final org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());
/**
* 文件上传
* @param file
*/
@ApiOperation("上传测试接口")
@RequestMapping(value = "/uploadBlog",method = RequestMethod.POST)
public String uploadBlog(@ApiParam(value="文件",required=true)@RequestPart("file") MultipartFile file){
String uploadUrl = "";
logger.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
uploadUrl = AliyunOSSUtil.upload(newFile);
}
}
}catch (Exception ex){
ex.printStackTrace();
}
return uploadUrl;
}
}