如何实现OSS文件上传之后,压缩并打包成.zip文件

如何实现OSS文件上传之后,压缩并打包成.zip文件

前言

本人菜鸟,如果有不对的地方,还望指正

思路

先将文件下载到dokcer容器上,然后再从dokcer容器上打包好后,交给前端页面下载,这次用到的是亚马逊的桶,前端是vue
先附上亚马逊桶的版本

        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>s3</artifactId>
            <version>2.17.77</version>
        </dependency>

然后是核心的链接代码,因为这次的项目是将所有的配置都存放到一张表里的,所以将查询表,然后将需要的核心密钥读取出来,再创建s3client(下边的代码我做了一些删改,使用的时候需要注意,本人的初衷本是想记录自己写过的代码防止忘记)

		//获取secretKey
		String secretKey = “”;
		//获取accessKey
		String accessKey ="";
		//判断是哪种运行环境的代码
		String evn ;
		String projectType1 = FrameworkInfo.getProjectType();
		if (projectType1.equalsIgnoreCase("test") || projectType1.equalsIgnoreCase("dev")){
			evn = "test";
		}else {
			evn = "run";
		}
		final String bucketName = bucketMap.get("fvalue"); // 替换为你的 S3 桶名
		final String prefix = ""+evn+""; // 替换为要下载文件的目录前缀
		BasicAWSCredentials AWS_CREDENTIALS = new BasicAWSCredentials(accessKey 
				, secretKey );
		AmazonS3 s3client = AmazonS3ClientBuilder.standard()
				.withCredentials(new AWSStaticCredentialsProvider(AWS_CREDENTIALS))
				.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("你的端点", ""))
				.build();

这个时候我们已经拿到了核心的s3client,通过这个s3client我们就可以访问我们当前目录下的所有文件了
接下来我们将需要下载的文件循环下载到当前的Dokcer上

			for (Map map : upInfoList){
				String key = “需要下载的文件Key”;
				System.out.println("Downloading: " + key);
				try (S3Object s3object = s3client.getObject(new GetObjectRequest(bucketName, key))) {
					InputStream objectData = s3object.getObjectContent();
					String downloadDir = ""; // 替换为保存目录
					//构造本地文件路径
					String fileName = “”;
					// 定义目录路径
					downloadDir = “”;
					// 转换为Path对象
					Path directory = Paths.get(downloadDir);
					// 检查目录是否存在
					if (!Files.exists(directory)) {
						try {
							// 如果目录不存在,则创建它
							Files.createDirectories(directory);
							System.out.println("目录已创建: " + downloadDir);
						} catch (IOException e) {
							// 创建目录时可能抛出IOException,需要处理
							e.printStackTrace();
						}
					} else {
						System.out.println("目录已存在: " + downloadDir);
					}
					File localFile = new File(downloadDir,fileName);
					// 使用FileOutputStream将对象数据写入本地文件
					try (FileOutputStream fileOutputStream = new FileOutputStream(localFile)) {
						byte[] buffer = new byte[1024];
						int bytesRead;
						while ((bytesRead = objectData.read(buffer)) != -1) {
							fileOutputStream.write(buffer, 0, bytesRead);
						}
					}
					// 关闭S3对象的内容流
					objectData.close();
					System.out.println("File downloaded and renamed to " + localFile.getAbsolutePath());
				}
			}

通过以上代码,完成一个写入的操作,当然也可以根据修改下载路径,完成一个对文件的分类行为,到目前为止,我们完成了一个从oss上面下载文件到Dokcer上的一个操作,接下来我们需要读取到这个文件,然后下载下来

        String param = request.getParameter("param");
        String filSrc = request.getParameter("filSrc");
        // 文件夹路径(示例,你可能需要从请求参数或配置中获取)
        String folderPath = "“; // 替换为本地保存目录
        Path directoryPath = Paths.get(folderPath);
        System.out.println("查看路径:"+directoryPath);
        try {
            // 检查目录是否存在
            if (Files.exists(directoryPath)) {
                System.out.println("有压缩文件");
                // ZIP文件名(示例,你可能需要根据需要设置)
                String zipFileName = param+".zip";
                String encodedZipFileName = URLEncoder.encode(zipFileName, "UTF-8");
                // 设置响应头,告知客户端这是一个ZIP文件并触发下载
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedZipFileName + "\"");
                // 获取输出流
                try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
                    File folder = new File(folderPath);
                    if (folder.exists()) {
                        zipFolder(folder, folder.getName(), zos);
                    } else {
                        throw new IOException("Folder not found: " + folderPath);
                    }
                }
            } else {
                System.out.println("无压缩文件");
                System.out.println("目录 " + directoryPath + " 不存在。");
            }
            deleteFile(filSrc);
        } catch (IOException e) {
            deleteFile(filSrc);
            e.printStackTrace();
            System.err.println("删除目录 " + directoryPath + " 时发生错误。");
        }

好了,目前为止,后端部分已经完成,最后就是前端的内容了

	            fetch(url)
                .then(response => response.blob())
                .then(blob => {
                    const url = window.URL.createObjectURL(blob);
                    const link = document.createElement('a');
                    link.href = url;
                    link.setAttribute('download', '下载文件.zip');
                    document.body.appendChild(link);
                    link.click();
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(link);
                    this_.isLoadingAll = false;
                    }
                });

以上就已经完成了
目前为止代码已经写完了,如果有不对的地方希望大佬能够指点一二,多谢

  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是java实现oss文件上传的示例代码: ``` import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.common.utils.IOUtils; import com.aliyun.oss.model.ObjectMetadata; import com.aliyun.oss.model.PutObjectRequest; import com.aliyun.oss.model.PutObjectResult; import java.io.FileInputStream; import java.io.InputStream; public class OSSUploadDemo { public static void main(String[] args) { String endpoint = "<yourEndpoint>"; String accessKeyId = "<yourAccessKeyId>"; String accessKeySecret = "<yourAccessKeySecret>"; String bucketName = "<yourBucketName>"; String objectName = "<yourObjectName>"; String filePath = "<yourFilePath>"; // 创建OSSClient实例 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); try { // 创建上传请求 PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new FileInputStream(filePath)); // 设置上传文件的元信息 ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(putObjectRequest.getInputStream().available()); putObjectRequest.setMetadata(metadata); // 执行上传操作并返回结果 PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest); System.out.println("上传功:" + putObjectResult.getETag()); } catch (Exception e) { System.out.println("上传失败:" + e.getMessage()); } finally { // 关闭OSSClient实例 ossClient.shutdown(); } } } ``` 其中,需要替换的变量如下: - `endpoint`:OSS服务的访问域名,例如`http://oss-cn-hangzhou.aliyuncs.com` - `accessKeyId`:访问OSS服务的AccessKeyId - `accessKeySecret`:访问OSS服务的AccessKeySecret - `bucketName`:存储文件的Bucket名称 - `objectName`:上传文件在Bucket中的Object名称 - `filePath`:要上传文件路径
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值