如何实现文件上传到阿里云OSS!!!(结合上传pdf使用)

devtools/2024/9/23 11:19:10/

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

对象存储 OSS_云存储服务_企业数据管理_存储-阿里云阿里云对象存储 OSS 是一款海量、安全、低成本、高可靠的云存储服务,提供 99.995 % 的服务可用性和多种存储类型,适用于数据湖存储,数据迁移,企业数据管理,数据处理等多种场景,可对接多种计算分析平台,直接进行数据处理与分析,打破数据孤岛,优化存储成本,提升业务价值。icon-default.png?t=N7T8https://www.aliyun.com/product/oss?spm=5176.8465980.unusable.ddetail.7df51450v1aNb1

二、创建存储空间

1、创建Bucket

 2、完成创建Bucket

 三、申请AccessKey

 

 四、代码实现

1、导入依赖

  <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即可。

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/ObjectNameStringBuilder stringBuilder = new StringBuilder("https://");stringBuilder.append(bucketName).append(".").append(endpoint).append("/").append(objectName);return stringBuilder.toString();}
}

3、配置阿里云OSS

aliyun.oss.bucketName = scl-oss-test
aliyun.oss.endpoint = oss-cn-beijing.aliyuncs.com
aliyun.oss.accessKeyId = 
aliyun.oss.accessKeySecret = 

4、配置相应model类

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容器中,便于后续的使用。

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@ConditionalOnMissingBeanpublic AliOssUtil getAliOssUtil(AliOssProperties aliOssProperties) {
//        log.info("创建OssUtil");AliOssUtil aliOssUtil = new AliOssUtil(aliOssProperties.getEndpoint(),aliOssProperties.getAccessKeyId(),aliOssProperties.getAccessKeySecret(),aliOssProperties.getBucketName());return aliOssUtil;}
}

五、结合上传pdf使用

上篇文章有介绍pdf使用。SpringBoot整合PDF动态填充数据并下载!!!-CSDN博客文章浏览阅读106次。TextPDF(现在也称为iText 7)是一款强大的Java库,专门用于创建、填充、阅读、操纵和维护PDF文档。:iTextPDF能够从零开始创建PDF文档,也可以读取已有的PDF文件并对其中的内容进行修改,如添加、删除或更新页面内容。:可以在PDF文档中插入文本、图片、图表等内容。:支持复杂表格的创建和填充,包括单元格合并、样式设定等。:支持创建和填充交互式PDF表单,包括文本字段、复选框、列表框等,并且可以对表单域进行读写操作。:提供对PDF文档进行数字签名的支持,确保文档的安全性和完整性。https://blog.csdn.net/qq_64847107/article/details/137959658?spm=1001.2014.3001.5502

1、将pdf模板上传到阿里云

 2、修改上传pdf的代码实现将pdf上传到阿里云

其实就是修改了三句代码:

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 {@Autowiredprivate 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);//上传到ossaliOssUtil.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));// 设置默认页面大小为A4pdf.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();}
}


http://www.ppmy.cn/devtools/4051.html

相关文章

API高频量化交易平台:数字货币市场的革新与挑战

在数字货币市场迅速发展的背景下&#xff0c;越来越多的普通投资者开始将注意力转向高频量化交易&#xff0c;将其视为一种稳定的投资策略。在这一趋势中&#xff0c;API高频量化交易平台&#xff0c;成为了众多投资者的首选。 作为数字货币投资的“闪电猎手”&#xff0c;高频…

美国家安全局等发布安全部署人工智能系统指南

该指南旨在为部署和运行由其他实体设计和开发的人工智能系统的组织提供最佳实践。 2024年4月15日&#xff0c;美国国家安全局发布了名为《安全部署人工智能系统&#xff1a;部署安全、弹性人工智能系统的最佳实践》&#xff0c;该指南旨在为部署和运行由其他实体设计和开发的人…

ArtCoder——通过风格转换生成多元化艺术风格二维码

简介 ArtCoder能够从原始图像&#xff08;内容&#xff09;、目标图像&#xff08;风格&#xff09;以及想要嵌入的信息中&#xff0c;生成具有艺术风格的二维码。这一过程类似于通常的图像风格转换&#xff0c;但特别针对二维码的特点进行了优化和调整。 通过这种方法&#…

2024 CKA 最新 | 基础操作教程(十六)

题目内容 设置配置环境&#xff1a; [candidatenode-1] $ kubectl config use-context wk8s Task 名为 node02 的 Kubernetes worker node 处于 NotReady 状态。 调查发生这种情况的原因&#xff0c;并采取相应的措施将 node 恢复为 Ready 状态&#xff0c;确保所做的任何…

python绝对导入与相对导入(包内导入)(在创建自己的包、模块或系统工程时会用到的知识)

Part 1 我们先上案例&#xff0c;再分析原因。 若在pycharm新建工程&#xff0c;再创立几个文件&#xff0c;文件结构如下图 也就是说&#xff0c;我们在工程下有文件test.py和文件夹p&#xff0c;在p下分别有run.py和tool.py两个文件 一开始&#xff0c;py文件中都为空&…

Mac idea启动vue项目的时候报Permission denied

问题 node_modules/.bin/vue-cli-service: Permission denied 原因, 权限不足. 解决方案 chmod 777 node_modules/.bin/vue-cli-service 这里的chmod 777 是给启动服务提高权限。 注意赋权路径一定要相同 最后再重新启动命令即可

有关栈的练习

栈练习1 给定一个栈&#xff08;初始为空&#xff0c;元素类型为整数&#xff0c;且小于等于 109&#xff09;&#xff0c;只有两个操作&#xff1a;入栈和出栈。先给出这些操作&#xff0c;请输出最终栈的栈顶元素。 操作解释&#xff1a; 1 表示将一个数据元素入栈&#xff…

ShardingSphere:强大的分布式数据库中间件【图文】

ShardingSphere的诞生 ShardingSphere的结构 Sharding-JDBC :它提供了一个轻量级的 Java 框架&#xff0c;在 Java 的 JDBC 层提供额外的服务。使用客户端直连数据库&#xff0c;以 jar 包形式提供服务&#xff0c;无需额外部署和依赖&#xff0c;可理解为增强版的 JDBC 驱动&…