需要强调的是,本地文件系统有目录的概念,但是在S3上没有目录的概念,其URI只是作为Object的key出现。这里顺便在添加的时候赋予该Object一个Public Read权限,以便可以匿名访问。
- File file = new File(localPath);
- // 默认添加public权限
- s3Client.putObject(new PutObjectRequest(bucketName, s3Path, file)
- .withCannedAcl(CannedAccessControlList.PublicRead));
(4) 多线程上传
在文件比较大的时候,有必要用多线程上传。
- TransferManager tm = new TransferManager(s3Client);
- TransferManagerConfiguration conf = tm.getConfiguration();
- int threshold = 4 * 1024 * 1024;
- conf.setMultipartUploadThreshold(threshold);
- tm.setConfiguration(conf);
- Upload upload = tm.upload(bucketName, s3Path, new File(localPath));
- TransferProgress p = upload.getProgress();
- while (upload.isDone() == false)
- {
- int percent = (int)(p.getPercentTransfered());
- System.out.print("\r" + localPath + " - " + "[ " + percent + "% ] "
- + p.getBytesTransfered() + " / " + p.getTotalBytesToTransfer() );
- // Do work while we wait for our upload to complete...
- Thread.sleep(500);
- }
- System.out.print("\r" + localPath + " - " + "[ 100% ] "
- + p.getBytesTransfered() + " / " + p.getTotalBytesToTransfer() );
- // 默认添加public权限
- s3Client.setObjectAcl(bucketName, s3Path, CannedAccessControlList.PublicRead);
- DeleteObjectRequest request = new DeleteObjectRequest(bucketName, s3Path);
- s3Client.deleteObject(request);
(6) 重命名Object
没有直接的命名接口,而是借用copy接口来实现。
重命名分为2步:(1) 调用copy接口,作一个拷贝
(2) 调用delete接口,删除原来的Object
- System.out.println(s3PathOld + " -> " + s3PathNew);
- S3Object obj = s3Client.getObject(new GetObjectRequest(bucketName, s3PathOld));
- s3Client.copyObject(bucketName, s3PathOld,
- bucketName, s3PathNew);
- deleteFile(s3PathOld);
3.Access Control权限设置
上面有个简单的ACL设置,一般也够用了。如果此篇受大家欢迎的话,我再补上更详细的说明。
