下载官方提供jar放在项目根目录下
添加pom.xml中jar引用本地jar,主要是医用第一个,后面是三个不引用,测试不会报错,但是项目运行会提示找不到bean,都引入就可以了
<!--天翼云OOS-->
<dependency>
<groupId>cn.ctyun</groupId>
<artifactId>ctyun-sdk-oss</artifactId>
<version>6.5.5</version>
<scope>system</scope>
<systemPath>${project.basedir}/third-party/oos-java-sdk-6.5.5.jar</systemPath>
</dependency>
<dependency>
<groupId>httpclient</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.7</version>
<scope>system</scope>
<systemPath>${project.basedir}/third-party/httpclient-4.5.7.jar</systemPath>
</dependency>
<dependency>
<groupId>httpcore</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.11</version>
<scope>system</scope>
<systemPath>${project.basedir}/third-party/httpcore-4.4.11.jar</systemPath>
</dependency>
<dependency>
<groupId>joda.time</groupId>
<artifactId>joda-time</artifactId>
<version>2.8.1</version>
<scope>system</scope>
<systemPath>${project.basedir}/third-party/joda-time-2.8.1.jar</systemPath>
</dependency>
测试类
package com.ruoyi.oos;
import com.amazonaws.AmazonClientException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.SDKGlobalConfiguration;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.S3ClientOptions;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.Upload;
import java.io.File;
import java.util.List;
public class OOSUtils {
public static final String OOS_ACCESS_ID = "注册账号可获取";
//OOS_ACCESS_KEY
public static final String OOS_ACCESS_KEY = "注册账号可获取";
//OOS_ENDPOINT
public static final String OOS_ENDPOINT = "oos-hazz.ctyunapi.cn";
public static final String BUCKET_NAME = "注册账号可获取";
public static void main(String[] args) throws Exception {
try {
AmazonS3 ossClient = getAmazonS3();
System.out.println("\n\n");
System.out.println("===========OOS Java Sample Boot OK!================\n\n\n");
//不使用V4签名
System.setProperty(SDKGlobalConfiguration.ENABLE_S3_SIGV4_SYSTEM_PROPERTY, "true");
listBuckets(ossClient);
//测试上传
testTransferManager(ossClient);
System.out.println(" congratulation! \n\n\n");
System.out.println("===========OOS Java Sample Test OK!================\n");
} catch (Exception ex) {
System.out.println("===Please check the next exception:===============");
throw ex;
}
}
//############################1111111#######################################
//1 Service GetService(ListBucket) 对于做Get请求的服务,返回请求者拥有的所有Bucket,
// 其中“/”表示根目录。该API只对验证用户有效,匿名用户不能执行该操作。
public static void listBuckets(AmazonS3 ossClient) {
List<Bucket> listBuckets = ossClient.listBuckets();
for (Bucket bucketInfo : listBuckets) {
System.out.println("listBuckets:"
+ "\t Name:" + bucketInfo.getName()
+ "\t CreationDate:" + bucketInfo.getCreationDate()
+ "\t Owner:" + bucketInfo.getOwner());
}
}
//4.3.14 分段上传高级别API
public static void testTransferManager(AmazonS3 ossClient) throws Exception {
String existingBucketName = "ehs";
String keyName = "2022-05-25.txt";
// String filePath = "D:\\tmp\\2.txt";
String filePath = "D:\\share\\pmdzd\\2022-05-25.txt";
TransferManager tm = new TransferManager(ossClient);
System.out.println("before upload");
// TransferManager processes all transfers asynchronously,
// so this call will return immediately.
Upload upload = tm.upload(
existingBucketName, keyName, new File(filePath));
System.out.println("in upload");
try {
// Or you can block and wait for the upload to finish
upload.waitForCompletion();
System.out.println("Upload complete.");
} catch (AmazonClientException amazonClientException) {
System.out.println("Unable to upload file, upload was aborted.");
amazonClientException.printStackTrace();
}
}
public static AmazonS3 getAmazonS3() {
ClientConfiguration clientConfig = new ClientConfiguration();
clientConfig.setConnectionTimeout(30 * 1000); //设置连接的超时时间,单位毫秒
clientConfig.setSocketTimeout(30 * 1000); //设置socket超时时间,单位毫秒
clientConfig.setProtocol(Protocol.HTTP); //设置http
//负载是否参与签名、设置参与
S3ClientOptions options = new S3ClientOptions();
options.setPayloadSigningEnabled(true);
/* 创建client*/
AmazonS3 ossClient = new AmazonS3Client(
new PropertiesCredentials(OOS_ACCESS_ID, OOS_ACCESS_KEY), clientConfig);
// 设置endpoint
ossClient.setEndpoint(OOS_ENDPOINT);
//设置选项
ossClient.setS3ClientOptions(options);
return ossClient;
}
}
测试完全没有问题,但是我写到页面点击按钮选择文件,上传时,就发现了一个需要注意的问题,下面是我单独写的上传
Controller
/**
* 通用上传请求(单个)
*/
@PostMapping("/upload")
public AjaxResult uploadFile(MultipartFile file) {
try {
// 上传文件路径
// 上传并返回新文件名称
String originalFilename = file.getOriginalFilename();
String newFileName = ossService.upload(file, originalFilename);
String url = newFileName;
AjaxResult ajax = AjaxResult.success();
ajax.put("url", url);
ajax.put("fileName", newFileName);
ajax.put("newFileName", newFileName);
ajax.put("originalFilename", originalFilename);
return ajax;
} catch (Exception e) {
return AjaxResult.error(e.getMessage());
}
}
把哪几个key,配置到配置文件application.yml中,下面service中会用到
# 文件上传 OOS (天翼云)
oos:
config:
access-key: **********
secret-key: ******************************
endpoint: ********
bucket: ***
service
package com.ruoyi.oos.service;
import com.amazonaws.AmazonClientException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.SDKGlobalConfiguration;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.S3ClientOptions;
import com.amazonaws.services.s3.model.DeleteObjectsRequest;
import com.amazonaws.services.s3.model.DeleteObjectsResult;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.Upload;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* 天翼云 oos
*
*/
@Service
public class OssService {
@Value("${oos.config.access-key}")
private String OOS_ACCESS_ID;
@Value("${oos.config.secret-key}")
private String OOS_ACCESS_KEY;
@Value("${oos.config.endpoint}")
private String OOS_ENDPOINT;
@Value("${oos.config.bucket}")
private String BUCKET_NAME;
/**
* 单文件上传
*
* @param mfile
* @param originalFilename
* @return
* @throws Exception
*/
public String upload(MultipartFile mfile, String originalFilename) throws Exception {
AmazonS3 ossClient = getAmazonS3();
//不使用V4签名
System.setProperty(SDKGlobalConfiguration.ENABLE_S3_SIGV4_SYSTEM_PROPERTY, "true");
//测试上传
File file = new File("/temp/" + originalFilename);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
FileCopyUtils.copy(mfile.getBytes(), file);
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
String remoteFilePath = DateUtils.getDate();
// 用户上传文件时指定的前缀。
String dir = remoteFilePath + "/";
String keyName = dir + UUID.randomUUID() + suffix;
TransferManager tm = new TransferManager(ossClient);
Upload upload = tm.upload(BUCKET_NAME, keyName, file);
System.out.println("上传中···");
try {
// Or you can block and wait for the upload to finish
upload.waitForCompletion();
System.out.println("上传完成.");
} catch (AmazonClientException amazonClientException) {
System.out.println("文件不可用, 上传失败.");
amazonClientException.printStackTrace();
}
return keyName;
}
/**
* 删除 文件
*
* @param keyNames
*/
public void deleteObjects(List<String> keyNames) {
DeleteObjectsRequest request = new DeleteObjectsRequest(BUCKET_NAME);
List<DeleteObjectsRequest.KeyVersion> keys = new ArrayList<DeleteObjectsRequest.KeyVersion>();
AmazonS3 ossClient = getAmazonS3();
for (String keyName : keyNames) {
DeleteObjectsRequest.KeyVersion key = new DeleteObjectsRequest.KeyVersion(keyName, null);
keys.add(key);
}
request.withKeys(keys);
DeleteObjectsResult result = ossClient.deleteObjects(request);
}
/**
* 创建客户端
*
* @return
*/
public AmazonS3 getAmazonS3() {
ClientConfiguration clientConfig = new ClientConfiguration();
clientConfig.setConnectionTimeout(30 * 1000); //设置连接的超时时间,单位毫秒
clientConfig.setSocketTimeout(30 * 1000); //设置socket超时时间,单位毫秒
clientConfig.setProtocol(Protocol.HTTP); //设置http
//负载是否参与签名、设置参与
S3ClientOptions options = new S3ClientOptions();
options.setPayloadSigningEnabled(true);
/* 创建client*/
AmazonS3 ossClient = new AmazonS3Client(
new PropertiesCredentials(OOS_ACCESS_ID, OOS_ACCESS_KEY), clientConfig);
// 设置endpoint
ossClient.setEndpoint(OOS_ENDPOINT);
//设置选项
ossClient.setS3ClientOptions(options);
return ossClient;
}
}
需要注意点,我认为是这个位置
//测试上传 File file = new File("/temp/" + originalFilename); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } FileCopyUtils.copy(mfile.getBytes(), file);
因为oos上传接口,必须使用file上传,但是我们controller拿到的是
MultipartFile mfile,所以需要变换一下