环境:springboot+vue
导入依赖:
<!--阿里云--> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.11.2</version> </dependency>
yml文件配置:
#文件上传--输入对应的信息 aliyun: oss: ... endpoint: ... accessKeyId: secretAccessKey: ... bucketName: ...
工具类:
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Component
public class OssUtils {
@Value("${aliyun.oss.accessKeyId}")
private String accessKeyId;
@Value("${aliyun.oss.secretAccessKey}")
private String secretAccessKey;
@Value("${aliyun.oss.endpoint}")
private String endPoint;
@Value("${aliyun.oss.bucketName}")
private String bucketName;
public String uploadOneFile(MultipartFile file) {
if (!(file.getOriginalFilename().endsWith(".png")) && !(file.getOriginalFilename().endsWith(".jpg"))) {
try {
throw new Exception("文件类型错误,只能为png或者jpg");
} catch (Exception e) {
e.printStackTrace();
}
}
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, secretAccessKey);
//设置文件名
Date date = new Date();
SimpleDateFormat dateFormat= new SimpleDateFormat("yyyyMMddhhmmss");
String fileName = dateFormat.format(date).toString()
+ UUID.randomUUID().toString().replace("-", "")
+ file.getOriginalFilename();
System.out.println("filename:"+fileName);
try {
// 创建PutObject请求。
ossClient.putObject(bucketName, fileName, file.getInputStream());
String url = "http://" + bucketName + "." + endPoint + "/" + fileName;
System.out.println(url);
return url;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
public List<String> uploadArrayFile(MultipartFile[] files) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, secretAccessKey);
List<String> list = new ArrayList<>();
try {
//设置文件名
for (MultipartFile file : files) {
Date date = new Date();
SimpleDateFormat dateFormat= new SimpleDateFormat("yyyyMMddhhmmss");
String fileName = dateFormat.format(date).toString()
+ UUID.randomUUID().toString().replace("-", "")
+ file.getOriginalFilename();
// 创建PutObject请求。
ossClient.putObject(bucketName, fileName, file.getInputStream());
String url = "http://" + bucketName + "." + endPoint + "/" + fileName;
// System.out.println(url);
list.add(url);
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return list;
}
public boolean deleteFile(String fileUrl) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, secretAccessKey);
/** oss删除文件是根据文件完成路径删除的,但文件完整路径中不能包含Bucket名称。
* 比如文件路径为:http://edu-czf.oss-cn-guangzhou.aliyuncs.com/2022/08/abc.jpg",
* 则完整路径就是:2022/08/abc.jpg
*/
int begin = ("http://" + bucketName + "." + endPoint + "/").length(); //找到文件路径的开始下标
String deleteUrl = fileUrl.substring(begin);
try {
// 删除文件请求
ossClient.deleteObject(bucketName, deleteUrl);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
Controller里面:
public class FreightController {
@Resource
private OssUtils ossUtils;
@PostMapping("uploadOneFile")
public String uploadFile(MultipartFile file) {
//返回上传oss的url
return ossUtils.uploadOneFile(file);
}
@PostMapping("uploadArrayFile")
public List<String> uploadArrayFile(MultipartFile[] files) {
//返回上传oss的url
return ossUtils.uploadArrayFile(files);
}
@PostMapping("deleteFile")
public boolean deleteFile( String fileUrl) {
//返回是否删除成功
return ossUtils.deleteFile(fileUrl);
}
}
前端vue === 来自elementui的图片上传:
<el-upload
class="avatar-uploader"
action="https://jsonplaceholder.typicode.com/posts/"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
<script>
export default {
data() {
return {
imageUrl: ''
};
},
methods: {
handleAvatarSuccess(res, file) {
this.imageUrl = URL.createObjectURL(file.raw);
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
}
}
}
</script>