在Springboot 项目中实现图片上传至阿里云OSS 的功能的实现过程
1.开通阿里云对象存储OSS 2.创建Bucket
创建完成后在 文件管理-文件列表 中可以管理文件
概览中可以查看访问端口
3.导入依赖 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <dependency > <groupId > com.aliyun.oss</groupId > <artifactId > aliyun-sdk-oss</artifactId > <version > 3.15.0</version > </dependency > <dependency > <groupId > commons-io</groupId > <artifactId > commons-io</artifactId > <version > 2.11.0</version > </dependency > <dependency > <groupId > commons-beanutils</groupId > <artifactId > commons-beanutils</artifactId > <version > 1.7.0</version > </dependency >
4.编写工具类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 package com.zgl.util;import com.aliyun.oss.OSS;import com.aliyun.oss.OSSClientBuilder;import com.aliyun.oss.model.ObjectMetadata;import org.apache.commons.io.FilenameUtils;import org.springframework.web.multipart.MultipartFile;import java.util.UUID;public class OssUpload { public static final String ali_domain = "Bucket域名" ; public static final String endpoint = "Endpoint(地域节点)" ; public static final String accessKeyId = "AccessKeyId" ; public static final String accessKeySecret = "AccessKey Secret" ; public static final String bucketName = "buckerName" ; public static String uploadImg (MultipartFile file) { try { String originalFilename = file.getOriginalFilename(); String extension = "." +FilenameUtils.getExtension(originalFilename); String uuid = UUID.randomUUID().toString().replaceAll("-" , "" ); String fileName = uuid+extension; OSS ossClient = new OSSClientBuilder ().build( endpoint, accessKeyId, accessKeySecret); ObjectMetadata meta = new ObjectMetadata (); meta.setContentType("image/jpg" ); ossClient.putObject( bucketName, fileName, file.getInputStream(), meta ); ossClient.shutdown(); return ali_domain + fileName; }catch (Exception e) { e.printStackTrace(); return null ; } } }
参数在阿里云的OSS管理控制台可以看到
其中AccessKeyId 和AccessKey Secret 可以在图片中的页面中得到
5.测试 Controller接口 1 2 3 4 5 6 7 @RestController public class TestController { @PostMapping("/upload") public String upload (MultipartFile file) { return OssUpload.uploadImg(file); } }
前端页面 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > Title</title > </head > <body > <form action ="/upload" method ="post" enctype ="multipart/form-data" > <input type ="file" name ="file" value ="上传图片" > <input type ="submit" value ="上传" > </form > </body > </html >
看到页面返回了图片的url,再到阿里云的控制台可以看到已经上传成功了
6.补充 规范化 原本是直接把配置信息写在类中,并直接调用工具类的静态方法。
规范化的写法应该是
配置信息写在 application-dev.yaml 中,而 application.yaml 引用dev中的配置
比如下面这个项目中的写法
在application-dev.yaml 中写配置信息,而在application.yaml 中引用即可
然后用一个配置属性类封装配置信息
将工具类中的方法不使用静态,而是通过配置类,将工具类交给IOC容器管理
通过@Autowired注入工具类对象,调用方法
新版补充 文档中心: 各语言SDK参考文档_对象存储 OSS-阿里云帮助中心 (aliyun.com)
新版的OSS在OSS_ACCESS_KEY_ID 和OSS_ACCESS_KEY_SECRET 的操作上有改动,需要将它们加入到本地电脑的系统变量中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 import com.aliyun.oss.ClientException;import com.aliyun.oss.OSS;import com.aliyun.oss.common.auth.*;import com.aliyun.oss.OSSClientBuilder;import com.aliyun.oss.OSSException;import com.aliyun.oss.model.PutObjectRequest;import com.aliyun.oss.model.PutObjectResult;import org.springframework.web.multipart.MultipartFile;import java.io.File;public class AliOssUtil { public static void upload (MultipartFile multipartFile) throws Exception { String endpoint = "https://oss-cn-hangzhou.aliyuncs.com" ; EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); String bucketName = "sky-take-out-bucket-zgl" ; String objectName = "test.png" ; OSS ossClient = new OSSClientBuilder () .build(endpoint, credentialsProvider); try { PutObjectRequest putObjectRequest = new PutObjectRequest ( bucketName, objectName, multipartFile.getInputStream()); PutObjectResult result = ossClient.putObject(putObjectRequest); } 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(); } } } }
1 2 3 4 5 <dependency > <groupId > com.aliyun.oss</groupId > <artifactId > aliyun-sdk-oss</artifactId > <version > 3.15.1</version > </dependency >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <dependency > <groupId > javax.xml.bind</groupId > <artifactId > jaxb-api</artifactId > <version > 2.3.1</version > </dependency > <dependency > <groupId > javax.activation</groupId > <artifactId > activation</artifactId > <version > 1.1.1</version > </dependency > <dependency > <groupId > org.glassfish.jaxb</groupId > <artifactId > jaxb-runtime</artifactId > <version > 2.3.3</version > </dependency >