1.导入依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2.配置application.yml
oss:
endpoint: oss-cn-beijing.aliyuncs.com
keyId: xxxx
keysecret: xxxx
bucketname: bucket-crowd-lizhihuan
webUrl: https://bucket-crowd-lizhihuan.oss-cn-beijing.aliyuncs.com
folder: crowd/project/othertest
3.启动类
@SpringBootApplication
public class DbBootSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(DbBootSpringBootApplication.class,args);
}
}
4.获取application.yml获取的配置项
package com.docin.lzh.util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Component
@Configuration
public class ConstantConfig {
@Value("${oss.endpoint}")
private String endpoint;
@Value("${oss.keyId}")
private String accessKeyId;
@Value("${oss.keysecret}")
private String accessKeySecret;
@Value("${oss.folder}")
private String folder;
@Value("${oss.bucketname}")
private String bucketName;
@Value("${oss.webUrl}")
private String webUrl;
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public String getAccessKeyId() {
return accessKeyId;
}
public void setAccessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
}
public String getAccessKeySecret() {
return accessKeySecret;
}
public void setAccessKeySecret(String accessKeySecret) {
this.accessKeySecret = accessKeySecret;
}
public String getFolder() {
return folder;
}
public void setFolder(String folder) {
this.folder = folder;
}
public String getBucketName() {
return bucketName;
}
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
public String getWebUrl() {
return webUrl;
}
public void setWebUrl(String webUrl) {
this.webUrl = webUrl;
}
}
5.封装一个实体类
package com.docin.lzh.pojo;
import java.io.Serializable;
public class FileDTO implements Serializable {
private Long fileSize;
private String fileAPUrl;
private String webUrl;
private String fileSuffix;
private String fileBucket;
private String oldFileName;
private String folder;
public FileDTO() {
}
public FileDTO(Long fileSize, String fileAPUrl, String webUrl, String fileSuffix, String fileBucket, String oldFileName, String folder) {
this.fileSize = fileSize;
this.fileAPUrl = fileAPUrl;
this.webUrl = webUrl;
this.fileSuffix = fileSuffix;
this.fileBucket = fileBucket;
this.oldFileName = oldFileName;
this.folder = folder;
}
public Long getFileSize() {
return fileSize;
}
public void setFileSize(Long fileSize) {
this.fileSize = fileSize;
}
public String getFileAPUrl() {
return fileAPUrl;
}
public void setFileAPUrl(String fileAPUrl) {
this.fileAPUrl = fileAPUrl;
}
public String getWebUrl() {
return webUrl;
}
public void setWebUrl(String webUrl) {
this.webUrl = webUrl;
}
public String getFileSuffix() {
return fileSuffix;
}
public void setFileSuffix(String fileSuffix) {
this.fileSuffix = fileSuffix;
}
public String getFileBucket() {
return fileBucket;
}
public void setFileBucket(String fileBucket) {
this.fileBucket = fileBucket;
}
public String getOldFileName() {
return oldFileName;
}
public void setOldFileName(String oldFileName) {
this.oldFileName = oldFileName;
}
public String getFolder() {
return folder;
}
public void setFolder(String folder) {
this.folder = folder;
}
}
6.封装上传阿里云工具类
package com.docin.lzh.util;
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 com.docin.lzh.pojo.FileDTO;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@Component
public class AliyunOSSUtil {
private static Logger logger = Logger.getLogger(AliyunOSSUtil.class);
@Autowired
private ConstantConfig constantConfig;
public FileDTO upLoad(File file) {
logger.info("------OSS文件上传开始--------" + file.getName());
String endpoint = constantConfig.getEndpoint();
System.out.println("获取到的Point为:" + endpoint);
String accessKeyId = constantConfig.getAccessKeyId();
String accessKeySecret = constantConfig.getAccessKeySecret();
String bucketName = constantConfig.getBucketName();
String fileHost = constantConfig.getFolder();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = format.format(new Date());
String uuid = UUID.randomUUID().toString().replace("-", "");
String suffix = file.getName().substring(file.getName().lastIndexOf(".") + 1);
if (file == null) {
return null;
}
OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
try {
if (!client.doesBucketExist(bucketName)) {
client.createBucket(bucketName);
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
client.createBucket(createBucketRequest);
}
String fileUrl = fileHost + "/" + (dateStr + "/" + uuid) + "-" + file.getName();
client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
PutObjectResult result = client.putObject(new PutObjectRequest(bucketName, fileUrl, file));
if (result != null) {
System.out.println(result);
logger.info("------OSS文件上传成功------" + fileUrl);
return new FileDTO(
file.length(),
fileUrl,
constantConfig.getWebUrl() + "/" + fileUrl,
suffix,
"",
bucketName,
fileHost
);
}
} catch (OSSException oe) {
logger.error(oe.getMessage());
} catch (ClientException ce) {
logger.error(ce.getErrorMessage());
} finally {
if (client != null) {
client.shutdown();
}
}
return null;
}
}
7.编写controller
@RequestMapping(value = "/uploadFile")
@ResponseBody
public FileDTO uploadBlog(@RequestParam("file") MultipartFile file) {
logger.info("文件上传");
String filename = file.getOriginalFilename();
System.out.println("要上传的文件名称:" + filename);
try {
if (file!=null) {
if (!"".equals(filename.trim())) {
File newFile = new File(filename);
FileOutputStream os = new FileOutputStream(newFile);
os.write(file.getBytes());
os.close();
file.transferTo(newFile);
return aliyunOSSUtil.upLoad(newFile);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
8.使用postman测试
{
"fileSize": 22667,
"fileAPUrl": "crowd/project/othertest/2021-04-25/ef316b6bade3424e8eecaf8e5588df4a-256144534.jpg",
"webUrl": "https://bucket-crowd-lizhihuan.oss-cn-beijing.aliyuncs.com/crowd/project/othertest/2021-04-25/ef316b6bade3424e8eecaf8e5588df4a-256144534.jpg",
"fileSuffix": "jpg",
"fileBucket": "",
"oldFileName": "bucket-crowd-lizhihuan",
"folder": "crowd/project/othertest"
}