自动上传指定文件夹下的所有文件到阿里云oss储存

本文介绍了如何在阿里云服务器上,利用PHP和ThinkPHP3.2框架,结合阿里云OSS SDK,实现指定文件夹的自动上传功能。首先获取accessKeyId和accessKeySecret,创建存储空间bucket,然后遍历并上传文件,最后设置定时任务以2秒间隔执行上传操作。

一、环境

1、阿里云服务器

2、php5.0+mysql+tinkphp3.2

3、oss储存的SDK

二、逻辑

第一步:去阿里云后台获取accessKeyId和accessKeySecret

第二步:到阿里云oss对象储存去创建存储空间bucket;获取OSS地址和bucket的空间名字

第三步:遍历指定文件夹及子文件夹下的所有文件

第四步:下载oss的sdk,实现上传到OSS的bucket

第五步;指定定时任务,每隔2秒执行一次(用来实现自动上传到OSS,如果是手动可以省略此步);

三、目录结构

将下载的SDK放在Vendor目录下。

四、代码

<?php
// 首页
namespace Home\Controller;
use Think\Controller;
use OSS\Core\OssException;//不然OssException 报错
class IndexController extends Controller {
    public function ossscript() {
        do{
            //$timing = M('one_timing')->where(array('id'=>1))->find();//通过后台控制数据库的数据 来控制此循环
            $timing['timing'] = 1;
            ignore_user_abort();//关掉浏览器,PHP脚本也可以继续执行.
            set_time_limit(0);// 通过set_time_limit(0)可以让程序无限制的执行下去
            $interval=2;// 每隔2秒运行
            //todo
            //echo t
### 实现Java程序自动将本地文件夹上传阿里云OSS 为了实现这一功能,可以利用阿里云提供的SDK来操作OSS服务。以下是详细的说明。 #### 1. 添加Maven依赖 首先,在项目的`pom.xml`中加入如下依赖以引入阿里云OSS SDK: ```xml <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.10.0</version> </dependency> ``` 此版本号应根据实际需求调整[^1]。 #### 2. 配置认证信息 创建一个名为`config.properties`的配置文件用于保存访问密钥和其他必要参数: ```properties accessKeyId=your-access-key-id accessKeySecret=your-access-key-secret bucketName=your-bucket-name endpoint=oss-cn-hangzhou.aliyuncs.com localFolderPath=/path/to/local/folder/ remoteFolderPrefix=path/in/oss/bucket/ scheduleIntervalMinutes=60 ``` 这些设置允许应用程序连接到特定区域中的指定存储桶并定义源路径和目标前缀。 #### 3. 编写核心逻辑代码 下面是一个简单的例子展示如何编写主要业务逻辑来进行批量上传,并支持进度条显示: ```java import com.aliyun.oss.OSS; import com.aliyun.oss.OssClientBuilder; import com.aliyun.oss.model.PutObjectRequest; import java.io.File; import java.util.Properties; import java.nio.file.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class OssUploader { private static final Logger logger = LoggerFactory.getLogger(OssUploader.class); public void uploadFiles() throws Exception { Properties props = new Properties(); try (InputStream input = Files.newInputStream(Paths.get("config.properties"))) { props.load(input); } String accessKeyId = props.getProperty("accessKeyId"); String accessKeySecret = props.getProperty("accessKeySecret"); String bucketName = props.getProperty("bucketName"); String endpoint = props.getProperty("endpoint"); OSS ossClient = new OssClientBuilder().build(endpoint, accessKeyId, accessKeySecret); Path localDirPath = Paths.get(props.getProperty("localFolderPath")); String remotePrefix = props.getProperty("remoteFolderPrefix").endsWith("/") ? props.getProperty("remoteFolderPrefix") : props.getProperty("remoteFolderPrefix") + "/"; if (!Files.isDirectory(localDirPath)) throw new NotDirectoryException(localDirPath.toString()); DirectoryStream<Path> stream = Files.newDirectoryStream(localDirPath); int totalFilesCount = 0; for (Path entry : stream) { if (entry.toFile().isFile()) ++totalFilesCount; } stream.close(); float progressPercentage = 0f; System.out.println("Starting Upload..."); stream = Files.newDirectoryStream(localDirPath); for (Path fileEntry : stream) { File file = fileEntry.toFile(); if (file.isFile()){ PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, remotePrefix + file.getName(), file); // 设置回调函数监控上传状态变化事件 putObjectRequest.setProgressCallback((bytesWritten, totalBytes) -> { double currentProgress = ((double) bytesWritten / totalBytes * 100); if(currentProgress >= Math.floor(progressPercentage)){ progressPercentage += 5; // 更新百分比增量 System.out.printf("\rUploading... %.2f%%", currentProgress); } }); ossClient.putObject(putObjectRequest); } } System.out.print("\nUpload Complete."); ossClient.shutdown(); } } ``` 这段代码实现了基本的功能,包括读取配置、建立客户端实例、遍历目录下的所有文件并将它们逐个上传到远程服务器上对应的子目录内,同时还提供了简单的命令行界面下可视化的传输进度指示器。 #### 4. 定时任务调度 对于定时执行的任务,可以选择Quartz这样的开源库来安排固定时间间隔运行上述方法;也可以通过Linux系统的cron作业或者Windows上的计划任务来调用编译后的JAR包完成相同的目的。这里给出基于Quartz的一个简单示例片段: ```java SchedulerFactory schedFact = new StdSchedulerFactory(); Scheduler scheduler = schedFact.getScheduler(); JobDetail job = JobBuilder.newJob(OssUploaderJob.class).withIdentity("uploadJob", "group1").build(); Trigger trigger = TriggerBuilder.newTrigger() .withSchedule(SimpleScheduleBuilder.simpleSchedule() .withIntervalInHours(Integer.parseInt( props.getProperty("scheduleIntervalHours"))) .repeatForever()) .build(); scheduler.scheduleJob(job, trigger); scheduler.start(); ``` 以上就是关于如何使用Java开发自动化工具定期或按需向阿里云OSS发送数据集的整体解决方案概述。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值