一:开通阿里云对象存储服务oss,创建bucket,获得密钥
二:在程序中集成上传文件功能
1.连接阿里云OSS对象存储服务器
声明一个配置属性的文件用于传入连接的参数
package com.sky.properties;import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;@Component
@ConfigurationProperties(prefix = "sky.alioss")
@Data
public class AliOssProperties {private String endpoint;private String accessKeyId;private String accessKeySecret;private String bucketName;}
为了充分解耦,声明一个配置属性的类,从外部注入连接的属性值
- @Component: 标注Spring管理的Bean,使用@Component注解在一个类上,表示将此类标记为Spring容器中的一个Bean
- @data:Lombok注解用于生成对应的getter和setter方法
-
@ConfigurationProperties(prefix = "sky.alioss"):负责属性的批量注入
application.yml主配置文件中的配置信息:
spring:profiles:
用开发环境的配置文件active: devsky:alioss:endpoint: ${sky.alioss.endpoint}bucket-name: ${sky.alioss.bucket-name}access-key-id: ${sky.alioss.access-key-id}access-key-secret: ${sky.alioss.access-key-secret}
真正是信息配置在:开发环境中:application-dev.yml中
通过配置多份不同环境的配置文件,再通过打包命令指定需要打包的内容之后进行区分打包
sky:alioss:endpoint: oss-cn-beijing.aliyuncs.combucket-name: waimaiguoaccess-key-id: ***************access-key-secret: *************
填写阿里云相关信息,用于连接阿里云
三:封装一个aliyunOssUtil工具类,用于上传文件并拼接返回上传的文件的路径
package com.sky.utils;import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayInputStream;@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {private String endpoint;private String accessKeyId;private String accessKeySecret;private String bucketName;/*** 文件上传** @param bytes* @param objectName* @return*/public String upload(byte[] bytes, String objectName) {// 创建OSSClient实例。OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);try {// 创建PutObject请求就是把图片上传到阿里云OSS上。ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));} catch (OSSException oe) {System.out.println("Caught an OSSException, which means your request made it to OSS, "+ "but was rejected with an error response for some reason.");System.out.println("Error Message:" + oe.getErrorMessage());System.out.println("Error Code:" + oe.getErrorCode());System.out.println("Request ID:" + oe.getRequestId());System.out.println("Host ID:" + oe.getHostId());} catch (ClientException ce) {System.out.println("Caught an ClientException, which means the client encountered "+ "a serious internal problem while trying to communicate with OSS, "+ "such as not being able to access the network.");System.out.println("Error Message:" + ce.getMessage());} finally {if (ossClient != null) {ossClient.shutdown();}}//文件访问路径规则 https://BucketName.Endpoint/ObjectNameStringBuilder stringBuilder = new StringBuilder("https://");stringBuilder.append(bucketName).append(".").append(endpoint).append("/").append(objectName);log.info("文件上传到:{}", stringBuilder.toString());return stringBuilder.toString();}
}
四:创建一个配置类用于生成工具类的bean交给spring容器管理
package com.sky.config;import com.sky.properties.AliOssProperties;
import com.sky.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
@Slf4j
public class OssConfiguration {@Bean
//需要把属性通过参数注入其中public AliOssUtil aliOssUtil(AliOssProperties aliOssProperties){log.info("创建阿里云上传文件对象:{}",aliOssProperties);return new AliOssUtil(aliOssProperties.getEndpoint(),aliOssProperties.getAccessKeyId(),aliOssProperties.getAccessKeySecret(),aliOssProperties.getBucketName());}
}
五:创建一个controller接受前端的请求
import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;import java.io.IOException;
import java.util.UUID;@RestController
@RequestMapping("/admin/common")
@Api (tags = "通用接口")
@Slf4j
public class commonController {@Autowiredprivate AliOssUtil aliOssUtil;@PostMapping("/upload")@ApiOperation("文件上传")public Result<String> upload(MultipartFile file){try {//接下来就是拼接文件名String originalFilename = file.getOriginalFilename();String substring = originalFilename.substring(originalFilename.lastIndexOf("."));String objectString= UUID.randomUUID()+substring;//第一参数为:文件的输入流;第二个参数为上传文件的名称;String upload = aliOssUtil.upload(file.getBytes(), objectString);return Result.success(upload);} catch (IOException e) {System.out.println("文件上传异常:"+e);}return Result.error(MessageConstant.UPLOAD_FAILED);}}
-
MultipartFile file:用于接收前端文件类型的参数
- UUID类负责生成一个新的文件名称;防止文件名称重复
-
return Result.success(upload)
最终返回给前端一个url,前端会请求这个路径回显图片