# Move and rename objects

> Rename or move objects with S4 native Move: console steps, the move=true parameter of CopyObject, examples in several languages, and limits.

> **Tip**
>
> Traditional object storage services (Tencent COS, Aliyun OSS, AWS S3) don't support a native Move operation. To rename an object, you have to copy it and then delete the original, which is expensive.

Bitiful S4 supports a native Move operation, letting you **move or rename files efficiently**.

|                    | Copy + delete                                        | S4 Move                                     |
| :----------------- | ---------------------------------------------------- | ------------------------------------------- |
| Data               | A full copy is made                                  | No copy; only the location changes          |
| Time               | Grows with file size                                 | Independent of file size                    |
| Intermediate state | Both copies may exist at once, or it may fail midway | None; it either succeeds or nothing changes |
| Metadata           | Depends on the implementation                        | Unchanged; the modification time is updated |

## In the console

In **File management (文件管理)**, click **… › Move (rename) (移动 (重命名))** on the right of the file, edit the full path, and confirm. For the rules, see [Manage files](https://docs.bitiful.com/en/bitiful-s4/handbook/objects.md).

## With the S3 API

Call the standard CopyObject and append `?move=true` to the copy source:

```http
PUT /new/photo.jpg HTTP/1.1
Host: my-bucket.s3.bitiful.net
x-amz-copy-source: /my-bucket/old/photo.jpg?move=true
```

`?deleteAfterCopy=true` has the same effect as `?move=true`. On success, S4 returns 200 and a `CopyObjectResult`, and the old object no longer exists.

The examples below move `old/照片 1.jpg` to `new/photo.jpg`. Except for Python and the AWS CLI, which encode automatically, you need to URL-encode the source path yourself in other languages.

```bash title="AWS CLI"
aws s3api copy-object \
  --bucket my-bucket \
  --key "new/photo.jpg" \
  --copy-source "my-bucket/old/照片 1.jpg?move=true" \
  --endpoint-url https://s3.bitiful.net --region cn-east-1
```

```python title="move.py"
import os

import boto3

s3 = boto3.client(
    "s3",
    endpoint_url="https://s3.bitiful.net",
    region_name="cn-east-1",
    aws_access_key_id=os.environ["S4_ACCESS_KEY"],
    aws_secret_access_key=os.environ["S4_SECRET_KEY"],
)


def move(bucket: str, src: str, dst: str) -> None:
    # When CopySource is a string, boto3 encodes it automatically
    s3.copy_object(Bucket=bucket, Key=dst, CopySource=f"{bucket}/{src}?move=true")


move("my-bucket", "old/照片 1.jpg", "new/photo.jpg")
```

```javascript title="move.mjs"
import { S3Client, CopyObjectCommand } from "@aws-sdk/client-s3";

const s3 = new S3Client({
  endpoint: "https://s3.bitiful.net",
  region: "cn-east-1",
  credentials: {
    accessKeyId: process.env.S4_ACCESS_KEY,
    secretAccessKey: process.env.S4_SECRET_KEY,
  },
});

async function move(Bucket, src, dst) {
  const encoded = src.split("/").map(encodeURIComponent).join("/");
  await s3.send(
    new CopyObjectCommand({ Bucket, Key: dst, CopySource: `${Bucket}/${encoded}?move=true` })
  );
}

await move("my-bucket", "old/照片 1.jpg", "new/photo.jpg");
```

```go title="main.go"
package main

import (
	"context"
	"log"
	"net/url"
	"os"
	"strings"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/credentials"
	"github.com/aws/aws-sdk-go-v2/service/s3"
)

func move(ctx context.Context, client *s3.Client, bucket, src, dst string) error {
	parts := strings.Split(src, "/")
	for i, p := range parts {
		parts[i] = url.PathEscape(p)
	}
	source := bucket + "/" + strings.ReplaceAll(strings.Join(parts, "/"), "+", "%2B") + "?move=true"
	_, err := client.CopyObject(ctx, &s3.CopyObjectInput{
		Bucket:     aws.String(bucket),
		Key:        aws.String(dst),
		CopySource: aws.String(source),
	})
	return err
}

func main() {
	client := s3.New(s3.Options{
		BaseEndpoint: aws.String("https://s3.bitiful.net"),
		Region:       "cn-east-1",
		Credentials: credentials.NewStaticCredentialsProvider(
			os.Getenv("S4_ACCESS_KEY"), os.Getenv("S4_SECRET_KEY"), ""),
	})
	if err := move(context.Background(), client, "my-bucket", "old/照片 1.jpg", "new/photo.jpg"); err != nil {
		log.Fatal(err)
	}
}
```

```php title="move.php"
<?php
require 'vendor/autoload.php';

$s3 = new Aws\S3\S3Client([
    'version'     => 'latest',
    'endpoint'    => 'https://s3.bitiful.net',
    'region'      => 'cn-east-1',
    'credentials' => [
        'key'    => getenv('S4_ACCESS_KEY'),
        'secret' => getenv('S4_SECRET_KEY'),
    ],
]);

function move(Aws\S3\S3Client $s3, string $bucket, string $src, string $dst): void
{
    $encoded = implode('/', array_map('rawurlencode', explode('/', $src)));
    $s3->copyObject([
        'Bucket'     => $bucket,
        'Key'        => $dst,
        'CopySource' => "{$bucket}/{$encoded}?move=true",
    ]);
}

move($s3, 'my-bucket', 'old/照片 1.jpg', 'new/photo.jpg');
```

## Avoid overwriting

If the destination already exists, it is **overwritten** by default. Add a conditional header to prevent this:

| Header                                 | Effect                                                             |
| :------------------------------------- | ------------------------------------------------------------------ |
| `If-None-Match: *`                     | Moves only if the destination doesn't exist; otherwise returns 412 |
| `If-Match: "<ETag>"`                   | Overwrites only if the destination is still the specified version  |
| `x-amz-copy-source-if-match: "<ETag>"` | Moves only if the source object is still the specified version     |

```bash
aws s3api copy-object \
  --bucket my-bucket --key "new/photo.jpg" \
  --copy-source "my-bucket/old/photo.jpg?move=true" \
  --if-none-match "*" \
  --endpoint-url https://s3.bitiful.net --region cn-east-1
```

`--if-none-match` requires a recent version of the AWS CLI. For the full details of conditional headers, see [Conditional requests](https://docs.bitiful.com/en/developer/s3/conditional-requests.md).

## Move an entire directory

There is no API for moving a directory. List the objects in the directory and move them one by one:

```python title="move_dir.py"
def move_dir(bucket: str, src_dir: str, dst_dir: str) -> None:
    # Reuses s3 and move from above; list everything first, then move, to avoid changing keys while listing
    keys = []
    for page in s3.get_paginator("list_objects_v2").paginate(Bucket=bucket, Prefix=src_dir):
        keys += [o["Key"] for o in page.get("Contents", []) if not o["Key"].endswith("/")]
    for key in keys:
        move(bucket, key, dst_dir + key[len(src_dir):])


move_dir("my-bucket", "old/", "archive/2026/")
```

## Permissions and limits

| Item              | Description                                                                                                                                                                          |
| :---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Permissions       | Read and write permissions on the source object, and write permission on the destination. See [Sub-user permissions](https://docs.bitiful.com/en/bitiful-s4/handbook/permissions.md) |
| Scope             | The source and destination must be in the same bucket                                                                                                                                |
| Object type       | Files only; directory objects aren't supported                                                                                                                                       |
| Changing metadata | You can't change metadata such as Content-Type during a move, and `MetadataDirective` has no effect. To change metadata, make a separate CopyObject call                             |
| Destination path  | The destination path can't start with the full key of the source object. For example, you can't move `photo` to `photo-2026/1.jpg`                                                   |
| Source path       | Objects whose keys contain `?` can't be moved this way, because everything after `?` is treated as parameters                                                                        |
| Not applicable    | Multipart copy (UploadPartCopy) doesn't support `move=true`                                                                                                                          |

## Error codes

| Status code | Error code           | Cause                                                                                   |
| :---------: | -------------------- | --------------------------------------------------------------------------------------- |
|     400     | `InvalidArgument`    | The source object doesn't exist, or it is a directory                                   |
|     400     | `InvalidCopyDest`    | The source and destination are the same                                                 |
|     400     | `InvalidMoveDest`    | A cross-bucket move, or the destination path violates the limits above                  |
|     403     | `AccessDenied`       | Missing read and write permissions on the source or write permission on the destination |
|     409     | `OperationAborted`   | Conflicts with a concurrent write; retry later                                          |
|     412     | `PreconditionFailed` | A conditional header isn't satisfied                                                    |
