dongxu6418 2013-12-20 13:40
浏览 102
已采纳

删除多个对象Amazon s3 PHP SDK

I'm having issues deleting multiple objects at once..

Using this library- https://github.com/aws/aws-sdk-php-laravel - I have no issues with anything else using the library (putting, getting, deleting single objects, etc.)

try {
        $s3 = AWS::get('s3');
        $s3->deleteObjects(array(
            'Bucket'  => $bucket,
            'Objects' => $json['attachmentArray']
        ));
        return "Success deleting files.";
    } catch (S3Exception $e) {
        return "There was an error.
";
    }

deleteObjects Amazon Docs- http://docs.aws.amazon.com/AmazonS3/latest/dev/DeletingMultipleObjectsUsingPHPSDK.html

I get returned "Success deleting files.";, but the files are not being deleted.

My bucket name is correct, and the $json['attachmentArray'] is in the right format according to the docs (again, I have no issues with other areas like put, get, delete)

Can anyone point out where I'm messing up? Thanks.

Edit:

Trying to give more info:

I am POSTing info from an Angular function to Laravel endpoint.

Here is the Angular function (Firebase URL hidden):

$scope.deleteFile = function() {

  var r=confirm("Are you sure you want to delete this task & of it's all attachments?");
  if (r==true)
    {
      var attachmentArray = [];

      var atttachData = new Firebase('https://*.firebaseio.com/attachments');
        atttachData.on('value', function(dataSnapshot) {  
           dataSnapshot.forEach(function(childSnapshot) {
            var key   = childSnapshot.val().key;
            // attachmentArray.push(key); I tried this
               attachmentArray.push({Key:key});

            });
           });
                method: "POST",
                url: '/delete_task',
                data: {attachmentArray:attachmentArray},
                headers: {'Content-Type': 'application/json'},
           }).success(function(data){
              console.log(data);
           });
    } 
}

And here is my Laravel controller that I am trying to make deleteObjects (with updated code from @Kevin Florida:

 public function delete_task() {
    $request = Request::instance();
    $task = $request->getContent(); 
    $json = json_decode($task, TRUE); 
    $bucket ='bucketname/team1';

    // return $json['attachmentArray'];
    $s3 = AWS::get('s3');
    if(!$s3->deleteObjects(array(
                'Bucket'  => $bucket,
                'Objects' => $json['attachmentArray']
            ))) {
     return "error";
    } else {
     return "success";
    }
}

Now this returns a 500 server error.. I think I'm formatting $json['attachmentArray']; incorrectly? Not sure ;/

Edit2:

Angular function

$scope.deleteFile = function() {

  var r=confirm("Are you sure you want to delete this task & of it's all attachments?");
  if (r==true)
    {
      var attachmentArray = [];

      var atttachData = new Firebase('https://***/attachments');
        atttachData.on('value', function(dataSnapshot) {  
           dataSnapshot.forEach(function(childSnapshot) {
            var url   = childSnapshot.val().url;
            var name  = childSnapshot.val().name;
            var id    = childSnapshot.val().id;
            var key   = childSnapshot.val().key;              
            attachmentArray.push(key);
            });
           });
      $http({
                method: "POST",
                url: '/delete_task',
                data: {team:$scope.team,attachmentArray:attachmentArray,lastSegment:lastSegment},
                headers: {'Content-Type': 'application/json'},
           }).success(function(data){
              console.log(data);
           });          
    } 
}

Laravel controller

public function delete_task() {
    $s3 = AWS::get('s3');
    $task = Input::all();
    $bucket ='teamite/team'.$task['team'];

    //make the array for Objects on this side
    foreach ($task['attachmentArray'] as $value) {
        $array[] = array('Key' => $value);
      }
     // return $task['attachmentArray'][0];

      $result = $s3->deleteObjects(array(
          'Bucket' => 'teamite/team1',
          'Objects' => $array
      ));

      return $result;
}

And I log this response in the console from Amazon:

=====================
Debug output of model
=====================

Model data
-----------

This data can be retrieved from the model object using the get() method of the model   (e.g. $model->get($key)) or accessing the model like an associative array (e.g. $model['key']).

[Deleted] => Array
    (
        [0] => Array
            (
                [Key] => 4700pzgds4i_ad.jpg
            )

        [1] => Array
            (
                [Key] => xxvu29ms4i_ad.jpg
            )

    )

[RequestId] => 477F0DA04101D82E

So it seems to be working correctly now.. But the objects are not being deleted? What else am I doing wrong? Going crazy on this one!

  • 写回答

3条回答 默认 最新

  • doubiaozhan0745 2013-12-20 23:04
    关注

    It actually looks like you are not referencing the files (S3 objects) correctly. The formatting of the request is fine, but the bucket name and keys may be wrong.

    Looking at:

    $bucket = 'teamite/team'.$task['team'];
    

    Is your bucket called "teamite/team1" or just "teamite"? Keep in mind that S3 has a flat structure. There are no "subbuckets". If you have things laid out in a nested file structure, then the paths, or pseudo-folders, need to be included as part of the key.

    For example, in this imaginary URL to an object in S3: http://s3.amazonaws.com/all-of-my-things/photos/2013/12/photo0005.jpg

    The bucket is all-of-my-things, and the key is photos/2013/12/photo0005.jpg.

    The deleteObjects() call you are making is returning successfully because of the idempotent nature of S3 operations. If you delete an object multiple times, it will return successfully every time. What you are seeing here is that you are deleting objects using the wrong keys. Those keys don't exist, and therefore are already deleted.

    Hopefully this helps. Don't be afraid to reach out on the module's issue tracker or directly on the SDK's issue tracker for problems like this when you are working directly with the SDK objects.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'