oss文件上传
oss文件上传:将前端中提交的图片数据,在后端解析成图片二进制文件,通过上传该二进制文件实现图片保存到oss
1.导入oss坐标
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
2.配置oss的信息:
alioss:
endpoint: oss-cn-***.com
access-key-id: LT****qANyA
access-key-secret: IyaQ********v3
bucket-name: h*****n
3.写propertises文件中拿到的oss基本信息类
@Component
@ConfigurationProperties(prefix = "tree.alioss")
@Data
public class AliOssProperties {
/**
* 上传oss服务对象信息
*/
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
}
4.oss文件上传工具类
@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请求。
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/ObjectName
StringBuilder stringBuilder = new StringBuilder("https://");
stringBuilder
.append(bucketName)
.append(".")
.append(endpoint)
.append("/")
.append(objectName);
log.info("文件上传到:{}", stringBuilder.toString());
return stringBuilder.toString();
}
}
5.使用oss工具类上传文件
@PostMapping("/upload")
public Result<String> fileupload(MultipartFile file) throws IOException {
try {
//获取文件名称
String originalFilename = file.getOriginalFilename();
//通过文件名获取文件类型 通过“.”截取后缀
String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
//构建新文件名称
String objectName = UUID.randomUUID().toString() + substring;
//文件的请求路径
String filePath = aliOssUtil.upload(file.getBytes(), objectName);
return Result.success(filePath);
} catch (IOException e) {
Result.error("文件上传出异常");
}
return Result.error("文件上传失败");
}