总说
过程参考黑马程序员SpringBoot3+Vue3全套视频教程,springboot+vue企业级全栈开发从基础、实战到面试一套通关_哔哩哔哩_bilibili
目录
总说
一、功能实现
1.1 Controller层
1.2 测试接口
一、功能实现
我们要将入门程序改为一个工具类
在utils目录下创建AliOssUtil
将Demo中的代码复制过来
代码如下:
public static void main(String[] args) throws Exception {// 以华东1(杭州)为例,endpoint:是服务器区域节点String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。//EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();String ACCESS_KEY_ID = "LTAI5tRrhg6TFMC9vRnE8PSa";String ACCESS_KEY_SECRET = "d4vDQAycnaNh1oXl6cLgFwXii2uPIV";// 填写Bucket名称String bucketName = "learn-project-test";// 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。String objectName = "001.png";// 填写Bucket所在地域。以华东1(杭州)为例,Region填写为cn-hangzhou。String region = "cn-hangzhou";// 使用 DefaultCredentialProvider 或 StaticCredentialsProviderCredentialsProvider credentialsProvider = new DefaultCredentialProvider(ACCESS_KEY_ID, ACCESS_KEY_SECRET);// 创建OSSClient实例。ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);OSS ossClient = OSSClientBuilder.create().endpoint(endpoint).credentialsProvider(credentialsProvider).clientConfiguration(clientBuilderConfiguration).region(region).build();try {// 填写字符串。String content = "Hello OSS,你好世界";// 创建PutObjectRequest对象//这里我们要上传图片,修改为:new FileInputStream("本地磁盘路径")PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new FileInputStream("C:\\Users\\86176\\Desktop\\files\\001.png"));// 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。// ObjectMetadata metadata = new ObjectMetadata();// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());// metadata.setObjectAcl(CannedAccessControlList.Private);// putObjectRequest.setMetadata(metadata);// 上传字符串。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();}}}
我们发现:endpoint、ACCESS_KEY_ID、ACCESS_KEY_SECRET、bucketName的值不会变,我们设置成全局变量,并修改endpoint、bucketName变量名
// 以华东1(杭州)为例,endpoint:是服务器区域节点private static final String ENDPOINT = "https://oss-cn-hangzhou.aliyuncs.com";// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。//EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();private static final String ACCESS_KEY_ID = "LTAI5tRrhg6TFMC9vRnE8PSa";private static final String ACCESS_KEY_SECRET = "d4vDQAycnaNh1oXl6cLgFwXii2uPIV";// 填写Bucket名称private static final String BUCKET_NAME = "learn-project-test";
对代码进行修改,修改完的完整代码如下:
package com.example.learnproject.utils;import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;import java.io.FileInputStream;
import java.io.InputStream;public class AliOssUtil {// 以华东1(杭州)为例,endpoint:是服务器区域节点private static final String ENDPOINT = "https://oss-cn-hangzhou.aliyuncs.com";// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。//EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();private static final String ACCESS_KEY_ID = "LTAI5tRrhg6TFMC9vRnE8PSa";private static final String ACCESS_KEY_SECRET = "d4vDQAycnaNh1oXl6cLgFwXii2uPIV";// 填写Bucket名称private static final String BUCKET_NAME = "learn-project-test";// 填写Bucket所在地域。以华东1(杭州)为例,Region填写为cn-hangzhou。private static final String region = "cn-hangzhou";//设置String类型访问地址,返回图片地址public static String uploadFile(String objectName, InputStream inputStream) throws Exception {// 使用 DefaultCredentialProvider 或 StaticCredentialsProviderCredentialsProvider credentialsProvider = new DefaultCredentialProvider(ACCESS_KEY_ID, ACCESS_KEY_SECRET);// 创建OSSClient实例。ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);OSS ossClient = OSSClientBuilder.create().endpoint(ENDPOINT).credentialsProvider(credentialsProvider).clientConfiguration(clientBuilderConfiguration).region(region).build();// 图片地址,用于返回String url = "";try {// 填写字符串。String content = "Hello OSS,你好世界";// 创建PutObjectRequest对象//这里我们要上传图片,修改为:new FileInputStream("本地磁盘路径")PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, objectName, inputStream);// 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。// ObjectMetadata metadata = new ObjectMetadata();// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());// metadata.setObjectAcl(CannedAccessControlList.Private);// putObjectRequest.setMetadata(metadata);// 上传字符串。PutObjectResult result = ossClient.putObject(putObjectRequest);// url组成:https://bucket名称.区域节点/时间/objectName名称url = "https://" + BUCKET_NAME + "." + ENDPOINT.substring(ENDPOINT.lastIndexOf("/") + 1) + "/" + objectName;} 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.1 Controller层
来到FileUploadController,我们之前写的静态的,修改代码如下:
@RestController
public class FileUploadController {@PostMapping("/upload")public Result<String> upload(MultipartFile file) throws Exception { //MultipartFile file 用来接收上传的文件//把文件的内容存到本地磁盘上String originFilename = file.getOriginalFilename();// 获取原始文件名//保证文件的名字唯一,防止文件名被覆盖//用UUID.randomUUID().toString() 生成一个随机的字符串 + 原始文件名后缀String fileName = UUID.randomUUID().toString() + originFilename.substring(originFilename.lastIndexOf("."));//file.transferTo(new File("C:\\Users\\86176\\Desktop\\files\\" + fileName));//将接收到的文件内容写入到本地磁盘上//第一个参数是String类型的文件路径,第二个参数是File类型的输入流String url = AliOssUtil.uploadFile(fileName, file.getInputStream());return Result.success(url);}
}
1.2 测试接口
来到apifox的稳健上传接口,我们再测试一下,上传一个新的图片
成功上传
上传git保存