2017-06-29 31 views
0

我正在開發一個項目,現在我需要在s3 php sdk api中使用其前綴重命名一個密鑰。我找不到它,如果有任何幫助。由於如何在s3中使用前綴重命名文件夾使用PHP sdk

function moveFile($oldPath,$newPath){ 
$oKey = $this->getKey($oldPath); 
$nKey = $this->getKey($newPath); 

try{ 
    // Copy an object. 
    $this->o->copyObject(array(
     'Bucket'  => $this->bucket, 
     'ACL' => 'public-read', 
     'Key'  => $nKey, 
     'CopySource' => "{$this->bucket}/{$oKey}" 
    )); 

    $this->deleteFile($oldPath); 

} catch (S3Exception $e) { 
    echo $e->getMessage() . "\n"; 
    return false; 
} 

}

+0

代碼是爲我工作到移動基於前綴的文件夾/鍵的功能。但我想知道是否有任何功能來重命名文件夾?喜歡這個? –

+0

[如何重命名Amazon S3中的文件和文件夾?](https://stackoverflow.com/questions/21184720/how-to-rename-files-and-folder-in-amazon-s3) – LuFFy

回答

0

您可以使用下面的代碼命名s3文件:

$s3sdk = new Sdk($awsConfig); 
$s3 = $s3sdk->createS3(); 
$s3->registerStreamWrapper(); 
rename($oldName, $newName); 

兩個名字需要包含完整S3路徑如:

"s3://yourBucketName/path/to/file" 

基本上registerStreamWrapper() zh可用於s3文件的PHP文件系統命令。

+1

謝謝你的答案也是正確的,但是我回答了上面的代碼。 –

1

我這樣做了,你們回答遲了。我自己做了,但Luffy的回答也是正確的。

function renameFolder($oldPath,$newPath){ 
$oKey = $this->getKey($oldPath); 
if(strpos($oKey,'/')==false){$oKey.='/';} 
//echo '<br>oKey: '.$oKey.'<br>'; 
try{ 
    // Copy an object. 
    /*$this->o->copyObject(array(
     'Bucket'  => $this->bucket, 
     'ACL' => 'public-read', 
     'Key'  => $nKey, 
     'CopySource' => "{$this->bucket}/{$oKey}" 
    ));*/ 

    $result = $this->o->listObjects([ 
     'Bucket' => $this->bucket, // REQUIRED 
     'Prefix' => $oKey, 
    ]); 

    foreach($result['Contents'] as $file){ 
     //echo '<br>objectKey: '.$file['Key'].'<br>'; 
     $nKey = str_replace($this->getLastKey($oldPath),$this->getLastKey($newPath),$file['Key']); 
     //echo '<br>nKey: '.$nKey.'<br>'; 
     $this->o->copyObject(array(
      'Bucket'  => $this->bucket, 
      'ACL' => 'public-read', 
      'Key'  => $nKey, 
      'CopySource' => "{$this->bucket}/".$file['Key']."" 
     )); 
    } 

    $this->deleteDir($oldPath); 

}catch(S3Exception $e) { 
    echo $e->getMessage() . "\n"; 
    return false; 
} 

}

相關問題