目录
- 引入maven依赖
- 编写ossUtil
- 编写Controller
- 使用接口工具进行测试
- 测试表单文件上传
- 测试base64文件上传
首先需要在阿里云上开通oss服务,并获取到以下四个信息
- endpoint: 购买的服务器节点地址
- accessKeyId: 接入的keyId
- accessKeySecret: 接入的key秘钥
- bucketName:桶名称,其实也就是一个文件夹
引入maven依赖
<!-- oss的SDK -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.17.4</version>
</dependency>
编写ossUtil
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
@Slf4j
@Component
public class OssUtil {
private static final String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
private static final String accessKeyId = "xxxx";
private static final String accessKeySecret = "xxxx";
private static final String bucketName = "bucketName";
/**
* 实现上传图片到OSS
* @param multipartFile file
* @return 返回访问路径
*/
public String upload(MultipartFile multipartFile) throws Exception{
// 获取上传文件的输入流
InputStream inputStream = multipartFile.getInputStream();
// 重命名文件,避免文件覆盖
String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) +"-"+ multipartFile.getOriginalFilename();
return upload(inputStream, fileName);
}
/**
* 上传流到OSS
* @param inputStream 输入流
* @param fileName 文件名
* @return 访问路径
*/
public String upload(InputStream inputStream,String fileName) {
// 上传文件到 OSS
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
ossClient.putObject(bucketName,fileName,inputStream);
// 访问路径: https://[bucketName].[endpointHost]/fileName
// 例如: https://zifeiyu01-oss.oss-cn-fuzhou.aliyuncs.com/20240220120000-1.jpg
String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
ossClient.shutdown();
return url;
}
/**
* base64转图片后上传流到OSS
* @param imgData base64字符串
* @return 访问路径
*/
public String uploadBase64(String imgData) throws Exception {
//处理根据日期生成目录
String dateDirPath = ResourceUtils.getURL("classpath:").getPath()+LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))+"/";
//生成随机文件名
String fileName = UUID.randomUUID().toString().replace("-","")+".jpg";
//检查目录,没有要先创建目录,不然 new FileOutputStream() 会报 FileNotFoundException异常
File folder = new File(dateDirPath);
if (!folder.exists()){
folder.mkdirs();
}
//合成最后临时文件路径
String imgFilePath = dateDirPath + fileName;
//base64编码 转 图片(imgData:base64编码,imgFilePath:生成图片的路径)
GenerateImage(imgData, imgFilePath);
File file = new File(imgFilePath);
InputStream inputStream = new FileInputStream(file);
return upload(inputStream,fileName);
}
/**
* base64转图片
* @param imgData base64字符串
* @param imgFilePath 生成的文件路径
*/
public static boolean GenerateImage(String imgData, String imgFilePath) throws IOException { // 对字节数组字符串进行Base64解码并生成图片
System.out.println("图片数据:"+imgData);
if (imgData == null) // 图像数据为空
return false;
FileOutputStream out = null;
try {
out = new FileOutputStream(new File(imgFilePath));
// Base64解码
byte[] b = Base64.decodeBase64(imgData);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
out.write(b);
} catch (FileNotFoundException e) {
log.error("文件未找到异常", e);
} finally {
if (out != null){
out.flush();
out.close();
}
return true;
}
}
// 测试base64转图片
public static void main(String[] args) throws Exception {
OssUtil ossUtil = new OssUtil();
String s = ossUtil.uploadBase64("iVBORw0KGgoAAAANSUhEUgAAAMcAAABHCAYAAACztVMeAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAHYcAAB2HAY/l8WUAAAgrSURBVHhe7Z2xb+JIFMbvD916i9VK65qaIjTbbBoaGpoUqWhyBbqDIkgR6BSiiChC0aIIohwoslCcCHOR3s0zhsyMZ8yQeDcGvp/0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d16Xs1hXDqfSvLavEcu7JY55Fp+LA6uRNolwaNBV06t5PSAK1XayGDF+oUjj6oT3yEQ7G+5168N8y3ruizKxBxCbbFP2sg261FPSVvltIgrVXop2kb2X2RzYfvNwStSefnGfc36htU7P6GuSKHkGyGvxD3Uql2vFSeWR8WrJvWmY+OK3pBTokmcTqzaJFW4qIs+aKtyBe9d1Tv2W2r1zUVZmYN1qq/3Euck3Q+1KCGbYyFOb5sPg6gKmLi6Ubm9S/WL7L8C7UL+zAFBv0EuwBzQXsoFmAPaS7kAc0B7KRdgDmgv5QLMAe2lXIA5oL2UC5mZA78aC22LOFZdyMwcpfYGb2gh6APFsepCZuY4utaXU0NQPsWx6kJm5hg/j+lz/bOxMxCUF3GMcqy6kJk5mPZ929ghCMqLOv924mhdT6bmYPhH0PF75FDexDG5yQ/0M5mbg3n674mO+8d00D5AFQv6MHHscQxyLHJMbsovMQcAuwDMAYAFmAMACzAHABZgDgAswBwAWIA5ALAAcwBghOh/js1KtfoVsB4AAAAASUVORK5CYII=");
System.out.println("访问路径:"+s);
}
}
编写Controller
import com.zxh.ip.dto.UploadReq;
import com.zxh.ip.utils.OssUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
@RequestMapping("/upload")
@RestController
public class UploadController {
@Resource
private OssUtil ossUtil;
@PostMapping("/base64")
public String upload(@RequestBody UploadReq req) throws Exception {
return ossUtil.uploadBase64(req.getBase64ImgData());
}
@PostMapping("/file")
public String upload(MultipartFile file) throws Exception {
return ossUtil.upload(file);
}
}
@Data
public class UploadReq {
private String base64ImgData;
}
使用接口工具进行测试
测试表单文件上传
测试base64文件上传
在OSS服务也可看到图片上传成功。