1. 引入依赖文件
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.jetlee</groupId>
<artifactId>oss</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>oss</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--aliyunOSS-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2. 配制文件
专门做一个配置文件,然后在使用中直接读取配置文件,这样方便后期管理,修改application.properties
# OSS相关配制
oss.file.endpoint=oss-cn-beijing.aliyuncs.com # 阿里云内网或者外网的访问地址
oss.file.keyid=# 阿里云控制台获取
oss.file.keysecret=# 阿里云控制台获取
oss.file.bucketname=jp-testfree #自己定义的块儿名称
oss.file.filehost=blog # 自己定义的路径名称
3. 定义常量类 ConstantProperties.java
常量类读取application.properties中定义的参数
package com.jetlee.oss.constant;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class ConstantProperties implements InitializingBean {
@Value("${oss.file.endpoint}")
private String oss_file_endpoint;
@Value("${oss.file.keyid}")
private String oss_file_keyid;
@Value("${oss.file.keysecret}")
private String oss_file_keysecret;
@Value("${oss.file.filehost}")
private String oss_file_filehost;
@Value("${oss.file.bucketname}")
private String oss_file_bucketname;
public static String OSS_END_POINT;
public static String OSS_ACCESS_KEY_ID;
public static String OSS_ACCESS_KEY_SECRET;
public static String OSS_BUCKET_NAME;
public static String OSS_FILE_HOST;
@Override
public void afterPropertiesSet() throws Exception{
OSS_END_POINT=oss_file_endpoint;
OSS_ACCESS_KEY_ID=oss_file_keyid;
OSS_ACCESS_KEY_SECRET=oss_file_keysecret;
OSS_BUCKET_NAME=oss_file_bucketname;
OSS_FILE_HOST=oss_file_filehost;
}
}
4. 编写阿里云工具类AliyunOSSUtil
package com.jetlee.oss.utils;
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.jetlee.oss.constant.ConstantProperties;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
public class AliyunOSSUtil {
public static String upload(File file) {
String endpoint = ConstantProperties.OSS_END_POINT;
String accessKeyId = ConstantProperties.OSS_ACCESS_KEY_ID;
String accessKeySecret = ConstantProperties.OSS_ACCESS_KEY_SECRET;
String bucketName = ConstantProperties.OSS_BUCKET_NAME;
String fileHost = ConstantProperties.OSS_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) {
return fileUrl;
}
} catch (OSSException oe) {
}
finally {
//关闭
ossClient.shutdown();
}
return null;
}
}
5. 写一个上传页面uplaod.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="/dealupload">
<p>文件:<input type="file" name="file"/></p>
<p><input type="submit" value="上传"/></p>
</form>
</body>
</html>
6. 编写一个文件上传控制器
package com.jetlee.oss.controller;
import com.jetlee.oss.utils.AliyunOSSUtil;
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.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
@Controller
public class UploadController {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(UploadController.class);
@RequestMapping(value = "/dealupload", method = RequestMethod.POST)
public String uploadBlog(MultipartFile file) {
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 "upload";
}
@RequestMapping(value = "/upload", method = RequestMethod.GET)
public String toUploadBlog() {
return "upload";
}
}