概要
Springboot集成阿里云OSS实现文件上传与删除上传的图片
整体架构流程
前提以及开通阿里云OSS服务,获取每个人的
accessKeyId accessKeySecret
导入pom坐标
<!--alibaba-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.15.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<!--no more than2.3.3-->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.3</version>
</dependency>
编写前端表单与图片提交业务(表单与图片一同提交)
<el-upload
action="#"
list-type="picture-card"
:auto-upload="false"
ref="pictureUpload"
:on-change="getInamg"
>
<i slot="default" class="el-icon-plus"></i>
</el-upload>
前端方法
// 文件上传
getInamg(file) {
this.file = file.raw;
},
axios
export function saveInfoService(data, file) {
var from = new FormData()
from.append('file', file);
for (let key in data) {
from.append(key, data[key])
}
return request({
url: '/firm/info',
method: 'post',
data: from,
headers: { 'Content-Type': 'application/json' },
})
}
页面使用axios方法
async save() {
let res =
this.saveFrom.id == null || this.saveFrom.id == ""
? await saveInfoService(this.saveFrom, this.file)
: await updateInfoService(this.saveFrom, this.file);
if (res.code == 200) {
this.dialogVisible = false;
this.$message.success(res.message);
}
this.getAll();
},
后端接收(新增操作)
@Autowired
private AliOSSUtils aliOSSUtils;
@PostMapping
public CommonResult saveFirmwareInfo(TzFirmInfo firmwareInfo, MultipartFile file) {
try {
if (file != null) {
// 上传图片
String upload = aliOSSUtils.upload(file);
firmwareInfo.setLogImage(upload);
}
firmwareInfo.setCreateTime(new Date());
firmwareInfo.setCheckInTime(new Date());
firmwareInfo.setStatus(1);
TzRoom room = new TzRoom();
room.setId(firmwareInfo.getRoomId());
room.setIsflag(2);
room.setType(2);
room.setUserId(Integer.parseInt(firmwareInfo.getId().toString()));
roomService.updateById(room);
} catch (IOException e) {
throw new RuntimeException(e);
}
return firmwareInfoService.save(firmwareInfo) ? CommonResult.success() : CommonResult.failed();
}
删除操作
@DeleteMapping("/{id}")
public CommonResult deleteFirmwareInfo(@PathVariable Long id) {
TzFirmInfo one = firmwareInfoService.getOne(new LambdaQueryWrapper<TzFirmInfo>().eq(TzFirmInfo::getId, id));
String logImage = one.getLogImage();
String substring = logImage.substring(logImage.lastIndexOf("/")+1, logImage.length());
System.out.println(substring);
aliOSSUtils.delete(substring);
return firmwareInfoService.removeById(id) ? CommonResult.success() : CommonResult.failed();
}
AliOSSUtils
package cn.consult.utils;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import io.lettuce.core.dynamic.annotation.Command;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
/**
* @author yan
* @describe "严禁过度自燃!"
* @time 2024/4/9 11:02:32
*/
@Component()
public class AliOSSUtils {
private String endpoint = "https://oss-cn-beijing.aliyuncs.com";
private String accessKeyId = "";
private String accessKeySecret = "";
private String bucketName = "";
/**
* 实现上传图片到OSS
*/
public String upload(MultipartFile multipartFile) throws IOException {
// 获取上传的文件的输入流
InputStream inputStream = multipartFile.getInputStream();
// 避免文件覆盖
String originalFilename = multipartFile.getOriginalFilename();
String fileName = UUID.randomUUID().toString().replaceAll("-", "") + originalFilename.substring(originalFilename.lastIndexOf("."));
//上传文件到 OSS
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
ossClient.putObject(bucketName, fileName, inputStream);
//文件访问路径
String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
// 关闭ossClient
ossClient.shutdown();
return url;
}
public void delete(String url){
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// 删除文件或目录。如果要删除目录,目录必须为空。
// url 必须是文件名
ossClient.deleteObject(bucketName, url);
} 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();
}
}
}
}