目录
一、使用阿里云
1.1 阿里云:
https://www.aliyun.com/daily-act/ecs/activity_selection?utm_content=se_1014453619
1.2 点击控制台,并进入对象存储oss
在进度注册登录后点击右上角的控制台,然后找到对象存储oss并点击
1.3 创建 Bucket
在创建Bucket时,对地域看各自是否有要求,在对读写权限选择时,一般是选择公共读。
1.4创建AccessKey
在进行创建AccessKey时,最好是自行下载一份进行存留,否则点击确定后是无法进行查看。
二、Java结合oss实现文件上传
2.1导入依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.3</version>
</dependency>
2.2使用OSS
这里推荐使用配置文件来控制阿里云的账号密码,以及公网等。觉得麻烦的也可以将其写入oss类中。
2.2.1配置类(.yml文件)
aliyun:
oss:
file:
endpoint:
keyid:
keysecret:
bucketname:
endpoint为地域节点,bucketname为创建的bucket的名称。而剩下的俩个是创建AccessKey的时候获得。
2.2.2获取配置类信息
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "aliyun.oss.file")
public class ConstantPropertiesUtils {
/**
* 对应地域地址
*/
@Value("${aliyun.oss.file.endpoint}")
private String endpoint;
/**
* 账号
*/
@Value("${aliyun.oss.file.keyid}")
private String keyId;
/**
* 密码
*/
@Value("${aliyun.oss.file.keysecret}")
private String keySecret;
/**
* 创建的bucket名
*/
@Value("${aliyun.oss.file.bucketname}")
private String bucketName;
public String getEndpoint() {
return endpoint;
}
public String getKeyId() {
return keyId;
}
public String getKeySecret() {
return keySecret;
}
public String getBucketName() {
return bucketName;
}
}
2.2.3oss实现类
@Component
public class ossUtils {
@Autowired
ConstantPropertiesUtils constantPropertiesUtils;
public String upload(MultipartFile file) throws IOException {
String endpoint = constantPropertiesUtils.getEndpoint();
String keyID = constantPropertiesUtils.getKeyId();
String keySEcert = constantPropertiesUtils.getKeySecret();
String bucketName = constantPropertiesUtils.getBucketName();
System.out.println(endpoint);
System.out.println(keyID);
System.out.println(keySEcert);
System.out.println(bucketName);
// 获取上传的文件的输入流
InputStream inputStream = file.getInputStream();
// 获取源文件名
String originalFilename = file.getOriginalFilename();
//避免重名,使用uuid+原文件后缀名
String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
//上传文件到 OSS
OSS ossClient = new OSSClientBuilder().build(endpoint, keyID, keySEcert);
ossClient.putObject(bucketName, fileName, inputStream);
//文件访问路径
String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
// 关闭ossClient
ossClient.shutdown();
// 把上传到oss的路径返回
return url;
}
}
2.2.3后端接收
@Autowired
private ossUtils utils;
@PostMapping("/uploadImg")
public R uploadImg(MultipartFile file) throws IOException {
String url = utils.upload(file);
return R.ok(url);
}
2.2.4前端发送
<el-form-item label="文件">
<el-upload
name="image"
class="avatar-uploader"
:action="uploadUrl" //路径
:headers="tokenInfo" //请求头携带的token
:accept="'image/jpeg,image/png'" // 文件格式
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
>
<img v-if="imageUrl" :src="imageUrl" class="avatar" /> //展示 imageUrl为二进制的数据源
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
//文件上传相关
handleAvatarSuccess(res, file) {
this.dataForm.image = res.msg; //oss存储的路径
this.imageUrl = URL.createObjectURL(file.raw); //二进制的数据源
},
beforeAvatarUpload(file) { //上传前进行文件格式的判断
const isJPG = file.type === "image/jpeg" || file.type === "image/jpg";
const isPNG = file.type === "image/png";
const isLt2M = file.size / 1024 / 1024 < 10;
if (!isJPG && !isPNG) {
this.$message.error("上传头像图片只能是 JPG 或 PNG 格式!");
}
if (!isLt2M) {
this.$message.error("上传头像图片大小不能超过 2MB!");
}
return (isJPG || isPNG) && isLt2M;
}