一、开通阿里云OSS对象存储服务


二、创建存储空间
1、创建Bucket


2、完成创建Bucket


三、申请AccessKey


四、代码实现
1、导入依赖
XML
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--hutool-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>选择你的版本</version>
</dependency>
2、创建对应的工具类AliOssUtil类,此代码是固定代码,直接CV即可。
java
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayInputStream;
@Data
@AllArgsConstructor
//固定代码,CV直接使用
public class AliOssUtil {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
/**
* 文件上传
*
* @param bytes :传入的文件要转为byte[]
* @param objectName :表示在oss中存储的文件名字。
* @return
*/
public String upload(byte[] bytes, String objectName) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
} 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();
}
}
//文件访问路径规则 https://BucketName.Endpoint/ObjectName
StringBuilder stringBuilder = new StringBuilder("https://");
stringBuilder
.append(bucketName)
.append(".")
.append(endpoint)
.append("/")
.append(objectName);
return stringBuilder.toString();
}
}
3、配置阿里云OSS

bash
aliyun.oss.bucketName = scl-oss-test
aliyun.oss.endpoint = oss-cn-beijing.aliyuncs.com
aliyun.oss.accessKeyId =
aliyun.oss.accessKeySecret =
4、配置相应model类
java
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "aliyun.oss")
@Data
public class AliOssProperties {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
}
5、将工具类配置到ioc容器中,便于后续的使用。
java
import com.fpl.model.AliOssProperties;
import com.fpl.utils.AliOssUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OssConfiguration {
@Bean
@ConditionalOnMissingBean
public AliOssUtil getAliOssUtil(AliOssProperties aliOssProperties) {
// log.info("创建OssUtil");
AliOssUtil aliOssUtil = new AliOssUtil(
aliOssProperties.getEndpoint(),
aliOssProperties.getAccessKeyId(),
aliOssProperties.getAccessKeySecret(),
aliOssProperties.getBucketName()
);
return aliOssUtil;
}
}
五、结合上传pdf使用
1、将pdf模板上传到阿里云

2、修改上传pdf的代码实现将pdf上传到阿里云
其实就是修改了三句代码:
java
package com.by.controller;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import com.by.util.AliOssUtil;
import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* 控制器类,用于处理PDF模板填充及下载请求
*/
@RestController
public class PdfController {
@Autowired
private AliOssUtil aliOssUtil;
/**
* 处理GET请求以下载填充了数据的PDF文件
*
* @param response HttpServletResponse对象,用于设置响应头和发送下载文件
* @return 响应实体,包含填充好数据的PDF字节流
* @throws IOException 如果读取或写入PDF文件时发生异常
*/
@GetMapping("/download")
public ResponseEntity<byte[]> test(HttpServletResponse response) throws IOException {
// 设置响应头,指示浏览器以附件形式下载文件,并设置文件名
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
String downloadFileName = System.currentTimeMillis() + ".pdf";
response.setHeader("Content-Disposition", "attachment;filename=" + downloadFileName);
// 准备需要填充到PDF模板中的数据
Map<String, String> dataMap = new HashMap<>();
dataMap.put("name", "可口可乐");
dataMap.put("code", "350ml");
// 填充数据并生成带数据的PDF字节流
byte[] pdfBytes = getPdf(dataMap);
//上传到oss
aliOssUtil.upload(pdfBytes, downloadFileName);
// 创建并返回包含填充后PDF字节流的响应实体
return new ResponseEntity<>(pdfBytes, headers, HttpStatus.CREATED);
}
/**
* 根据提供的数据填充PDF模板并返回填充后的PDF字节流
*
* @param dataMap 需要填充到PDF模板中的键值对数据
* @return 填充好数据的PDF文件字节数组
* @throws IOException 如果读取或写入PDF文件时发生异常
*/
private byte[] getPdf(Map<String, String> dataMap) throws IOException {
//获取阿里云OSS上传的pdf模板
String fileUrl = "https://scl-oss-test.oss-cn-beijing.aliyuncs.com/1.pdf";
//将文件下载后保存在E盘,返回结果为下载文件大小
long size = HttpUtil.downloadFile(fileUrl, FileUtil.file("C:/Users/admin/Desktop"));
// 获取PDF模板文件路径
File sourcePdf = ResourceUtils.getFile("C:/Users/admin/Desktop/1.pdf");
// 使用PDF阅读器加载模板文件
PdfReader pdfReader = new PdfReader(new FileInputStream(sourcePdf));
// 创建一个内存输出流用于存储填充好数据的PDF文件
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// 创建PDF文档对象,连接读取器和输出流
PdfDocument pdf = new PdfDocument(pdfReader, new PdfWriter(outputStream));
// 设置默认页面大小为A4
pdf.setDefaultPageSize(PageSize.A4);
// 获取PDF表单域对象
PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);
Map<String, PdfFormField> fields = form.getFormFields();
// 设置字体,这里使用的是"STSong-Light"字体
PdfFont currentFont = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H", PdfFontFactory.EmbeddingStrategy.PREFER_NOT_EMBEDDED);
// 遍历待填充的数据,并将其填入对应的表单域
dataMap.forEach((key, value) -> {
Optional<PdfFormField> formFieldOptional = Optional.ofNullable(fields.get(key));
formFieldOptional.ifPresent(formField -> {
// 设置字体并替换表单域的值
formField.setFont(currentFont).setValue(value);
});
});
// 锁定并合并所有表单域,使其无法再编辑
form.flattenFields();
// 关闭PDF文档,释放资源
pdf.close();
// 将填充好的PDF文件转换为字节数组并返回
return outputStream.toByteArray();
}
}
