PutObjectCommand
The PutObjectCommand is used to upload a new object or update an existing object in your DID Space. This command is versatile and can handle various data types, such as files, strings, or buffers, making it the primary method for adding content to your space.
Usage Scenario#
You should use PutObjectCommand whenever you need to:
- Upload a new file (e.g., an image, a document, or a configuration file).
- Create a folder by providing a key that ends with a
/and no data. - Update the content or metadata of an existing file.
Input#
The PutObjectCommand requires the following input parameters to specify the object's location, content, and metadata.
Output#
The command returns a standard output object after the operation is complete.
Example: Uploading a Text File#
Here's a complete example of how to initialize the SpaceClient and use PutObjectCommand to upload a simple text file.
Example: Uploading a file
import { SpaceClient, PutObjectCommand } from '@blocklet/did-space-js';
import getWallet from '@blocklet/sdk/lib/wallet';
async function uploadFile() {
const client = new SpaceClient({
auth: {
endpoint: 'https://www.didspaces.com/app/api/space/...',
wallet: getWallet(),
},
});
const command = new PutObjectCommand({
key: 'greetings.txt',
data: 'Hello, DID Space!',
metadata: {
contentType: 'text/plain',
source: 'my-application',
},
});
const output = await client.send(command);
if (output.statusCode === 200) {
console.log('File uploaded successfully!');
} else {See all 5 lines
Example Response
Response
{
"statusCode": 200,
"statusMessage": "OK",
"data": undefined
}In this example, a file named greetings.txt with the content "Hello, DID Space!" is uploaded to the root of the space. We also include custom metadata to specify the content type and the source application.
Best Practices#
- Use Metadata: Attaching metadata to your objects is a great way to store additional context without altering the object's content. This can be very useful for filtering, organizing, and processing files later on.
- Handling Large Files: The SDK handles the complexities of multipart uploads for you. Simply provide the data, and the client will manage the streaming and transfer efficiently.
- Error Handling: Always check the
statusCodein the output to confirm that the upload was successful. A200status code means success, while other codes indicate potential issues that your application should handle.