目录
- 引入maven依赖
- 编写ossUtil
- 编写Controller
- 使用接口工具进行测试
- 测试表单文件上传
- 测试base64文件上传
首先需要在阿里云上开通oss服务,并获取到以下四个信息
- endpoint: 购买的服务器节点地址
- accessKeyId: 接入的keyId
- accessKeySecret: 接入的key秘钥
- bucketName:桶名称,其实也就是一个文件夹
引入maven依赖
<!-- oss的SDK --><dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.17.4</version></dependency>
编写ossUtil
import com.aliyun.oss.OSS;import com.aliyun.oss.OSSClientBuilder;import lombok.extern.slf4j.Slf4j;import org.apache.commons.codec.binary.Base64;import org.springframework.stereotype.Component;import org.springframework.util.ResourceUtils;import org.springframework.web.multipart.MultipartFile;import java.io.*;import java.time.LocalDateTime;import java.time.format.DateTimeFormatter;import java.util.UUID;@Slf4j@Componentpublic class OssUtil { private static final String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; private static final String accessKeyId = "xxxx"; private static final String accessKeySecret = "xxxx"; private static final String bucketName = "bucketName"; /** * 实现上传图片到OSS * @param multipartFile file * @return 返回访问路径 */ public String upload(MultipartFile multipartFile) throws Exception{ // 获取上传文件的输入流 InputStream inputStream = multipartFile.getInputStream(); // 重命名文件,避免文件覆盖 String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) +"-"+ multipartFile.getOriginalFilename(); return upload(inputStream, fileName); } /** * 上传流到OSS * @param inputStream 输入流 * @param fileName 文件名 * @return 访问路径 */ public String upload(InputStream inputStream,String fileName) { // 上传文件到 OSS OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); ossClient.putObject(bucketName,fileName,inputStream); // 访问路径: https://[bucketName].[endpointHost]/fileName // 例如: https://zifeiyu01-oss.oss-cn-fuzhou.aliyuncs.com/20240220120000-1.jpg String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName; ossClient.shutdown(); return url; } /** * base64转图片后上传流到OSS * @param imgData base64字符串 * @return 访问路径 */ public String uploadBase64(String imgData) { // 获取文件扩展名 String fileExt = "jpeg"; // 默认jpeg if (imgData.contains(";")){ fileExt = imgData.split(";")[0].split("/")[1]; imgData = imgData.split(",")[1]; //截取base64字符串 } //生成随机文件名 String fileName = UUID.randomUUID().toString().replace("-","")+"."+fileExt; return upload(base64StringToInputStream(imgData),fileName); } /** * base64转字节数组输入流 * 不生成本地图片,可直接用于上传OSS * @param imgData base64字符串 */ public static ByteArrayInputStream base64StringToInputStream(String base64String) { // 解码Base64字符串 byte[] decodedBytes = Base64.decodeBase64(base64String); // 创建ByteArrayInputStream return new ByteArrayInputStream(decodedBytes); } // 测试base64转图片 public static void main(String[] args) throws Exception { OssUtil ossUtil = new OssUtil(); String s = ossUtil.uploadBase64("iVBORw0KGgoAAAANSUhEUgAAAMcAAABHCAYAAACztVMeAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAHYcAAB2HAY/l8WUAAAgrSURBVHhe7Z2xb+JIFMbvD916i9VK65qaIjTbbBoaGpoUqWhyBbqDIkgR6BSiiChC0aIIohwoslCcCHOR3s0zhsyMZ8yQeDcGvp/0SavYY8b2+zxvnoflDwIAGIE5ALAAcwBgAeYAwALMAYAFmAMACzAHABZgDgAswBwAWIA5ALAAcwBgAeYAwALMAYAFmAMACzAHABZgDgAswBwAWIA5ALDwS8zx9N8THfeP6aB9QF/++kKf/vwEQb9dHHscgxyLHJObkrk5zifn9PXvr8bOQtBHiWOSY3MTMjVHd9I1dgyC8qJNDJKZOYJ5gBEDyr04Rh/nj3HUppOZOU4GJ8bOQFDexLHqQmbm+HH+w9gRCMqbOFZdyMwc3xrfjB2BoLyJY9WFzMxh6gQE5VUuwBzQXsoFmAPaS7kAc0B7KRfyZ46rHgXxMV0IXwLyH3vUvCyYj7crOi1TfTIifx7GZ86Ic5+2qHJq2D9NjRMavMSHYOY9qpr222G5sPXmeCUkf1Ilz3TMLZd31SVfDmad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hH0PF75FDexDG5yQ/0M5mbg3n674mO+8d00D5AFQv6MHHscQxyLHJMbsovMQcAuwDMAYAFmAMACzAHABZgDgAswBwAWIA5ALAAcwBghOh/js1KtfoVsB4AAAAASUVORK5CYII="); System.out.println("访问路径:"+s); }}
编写Controller
import com.zxh.ip.dto.UploadReq;import com.zxh.ip.utils.OssUtil;import org.springframework.web.bind.annotation.*;import org.springframework.web.multipart.MultipartFile;import javax.annotation.Resource;@RequestMapping("/upload")@RestControllerpublic class UploadController { @Resource private OssUtil ossUtil; @PostMapping("/base64") public String upload(@RequestBody UploadReq req) throws Exception { return ossUtil.uploadBase64(req.getBase64ImgData()); } @PostMapping("/file") public String upload(MultipartFile file) throws Exception { return ossUtil.upload(file); }}
@Datapublic class UploadReq { private String base64ImgData;}
使用接口工具进行测试
测试表单文件上传
测试base64文件上传
在OSS服务也可看到图片上传成功。