<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.15.1</version>
</dependency>
后端获取文件方法类:
MultipartFile
获取名字的用途是为了获取后缀名。
OSS的工具类:
package com.quxiao.util;
import com.aliyun.oss.*;
import com.aliyun.oss.model.GetObjectRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.UUID;
@PropertySource(value = "classpath:application.yml")
@Component
public class AliOssUtil {
private String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
@Value("${oss.accessKeyId}")
private String accessKeyId;//密钥id
@Value("${oss.accessKeySecret}")
private String accessKeySecret;//密钥
// 填写Bucket名称,例如examplebucket。
@Value("${oss.bucketName}")
private String bucketName;
public String addImg(InputStream file, String type) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
//通过传入bucketName名,文件名名,以及文件流上传到oss
String imgName = UUID.randomUUID().toString() + type;
ossClient.putObject(bucketName, imgName, file);
//返回文件地址,服务器保存
return endpoint.substring(0, 8) + bucketName + "." + endpoint.substring(8) + "/" + imgName;
} 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();
}
}
return "-1";
}
}
controller层:
package com.quxiao.controller;
import com.quxiao.util.AliOssUtil;
import com.quxiao.util.ReturnData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
/**
* @program: springboot
* @author: quxiao
* @create: 2023-05-17 08:15
**/
@RestController
public class UserController {
@Autowired
AliOssUtil aliOssUtil;
@RequestMapping("/t1")
public ReturnData t1(MultipartFile file) throws IOException {
String name = file.getOriginalFilename();
String s = aliOssUtil.addImg(file.getInputStream(), "." + name.substring(name.lastIndexOf(".") + 1));
return new ReturnData(1, "1", s);
}
}