File upload, download, and management with support for Amazon S3 and custom storage providers. Provides comprehensive object storage capabilities with features like multipart uploads, access control, and metadata management.
import {
uploadData, downloadData, list, remove,
getProperties, getUrl, copy
} from "aws-amplify/storage";For S3-specific functionality:
import {
uploadData, downloadData, list, remove,
getProperties, getUrl, copy
} from "aws-amplify/storage/s3";Upload files and data to storage with support for various input formats.
/**
* Upload data to storage
* @param input - Upload configuration including data and options
* @returns Promise with upload result and progress tracking
*/
function uploadData(input: UploadDataInput): UploadTask;
interface UploadDataInput {
key: string;
data: UploadDataSource;
options?: {
accessLevel?: 'guest' | 'protected' | 'private';
contentType?: string;
contentDisposition?: string;
contentEncoding?: string;
contentLanguage?: string;
expires?: Date;
metadata?: Record<string, string>;
tagging?: Record<string, string>;
onProgress?: (progress: TransferProgress) => void;
preventOverwrite?: boolean;
checksumAlgorithm?: 'CRC32' | 'CRC32C' | 'SHA1' | 'SHA256';
};
}
type UploadDataSource =
| Blob
| File
| ArrayBuffer
| string;
interface UploadTask {
result: Promise<UploadDataOutput>;
cancel(): void;
pause(): void;
resume(): void;
state: 'NOT_STARTED' | 'IN_PROGRESS' | 'PAUSED' | 'CANCELLED' | 'SUCCESS' | 'ERROR';
}
interface UploadDataOutput {
key: string;
eTag?: string;
versionId?: string;
contentType: string;
metadata?: Record<string, string>;
}
interface TransferProgress {
transferredBytes: number;
totalBytes?: number;
}Usage Examples:
import { uploadData } from "aws-amplify/storage";
// Upload a file
const fileInput = document.getElementById('file') as HTMLInputElement;
const file = fileInput.files[0];
const uploadTask = uploadData({
key: `uploads/${file.name}`,
data: file,
options: {
contentType: file.type,
accessLevel: 'private',
metadata: {
uploadedBy: 'user123',
category: 'documents'
},
onProgress: (progress) => {
console.log(`Upload progress: ${progress.transferredBytes}/${progress.totalBytes}`);
}
}
});
// Get the result
const { key } = await uploadTask.result;
console.log('Upload completed:', key);
// Upload text data
const textUpload = uploadData({
key: 'data/sample.txt',
data: 'Hello, World!',
options: {
contentType: 'text/plain',
accessLevel: 'public'
}
});
await textUpload.result;Control upload operations with pause, resume, and cancel.
const uploadTask = uploadData({
key: 'large-file.zip',
data: largeFile
});
// Pause upload
uploadTask.pause();
// Resume upload
uploadTask.resume();
// Cancel upload
uploadTask.cancel();
// Monitor state
console.log('Upload state:', uploadTask.state);Download files and data from storage.
/**
* Download data from storage
* @param input - Download configuration
* @returns Promise with download result
*/
function downloadData(input: DownloadDataInput): DownloadTask;
interface DownloadDataInput {
key: string;
options?: {
accessLevel?: 'guest' | 'protected' | 'private';
targetIdentityId?: string;
bytesRange?: {
start: number;
end: number;
};
onProgress?: (progress: TransferProgress) => void;
};
}
interface DownloadTask {
result: Promise<DownloadDataOutput>;
cancel(): void;
}
interface DownloadDataOutput {
key: string;
body: Blob;
eTag?: string;
lastModified?: Date;
contentType?: string;
contentLength?: number;
metadata?: Record<string, string>;
}Usage Examples:
import { downloadData } from "aws-amplify/storage";
// Download a file
const downloadTask = downloadData({
key: 'uploads/document.pdf',
options: {
accessLevel: 'private',
onProgress: (progress) => {
console.log(`Download progress: ${progress.transferredBytes}/${progress.totalBytes}`);
}
}
});
const { body, contentType } = await downloadTask.result;
// Convert to text (for text files)
const text = await body.text();
// Convert to array buffer (for binary files)
const arrayBuffer = await body.arrayBuffer();
// Create object URL for display
const objectUrl = URL.createObjectURL(body);
// Download byte range
const partialDownload = downloadData({
key: 'large-file.zip',
options: {
bytesRange: {
start: 0,
end: 1023 // First 1KB
}
}
});List objects and directories in storage.
/**
* List objects in storage
* @param input - List configuration (optional)
* @returns Promise with list results
*/
function list(input?: ListInput): Promise<ListOutput>;
interface ListInput {
prefix?: string;
options?: {
accessLevel?: 'guest' | 'protected' | 'private';
targetIdentityId?: string;
pageSize?: number;
nextToken?: string;
delimiter?: string;
listAll?: boolean;
};
}
interface ListOutput {
results: StorageItem[];
nextToken?: string;
hasNextPage: boolean;
}
interface StorageItem {
key: string;
size?: number;
eTag?: string;
lastModified?: Date;
metadata?: Record<string, string>;
}Usage Examples:
import { list } from "aws-amplify/storage";
// List all objects
const { results } = await list();
console.log('All objects:', results);
// List objects with prefix
const { results: uploads } = await list({
prefix: 'uploads/',
options: {
accessLevel: 'private',
pageSize: 50
}
});
// List with pagination
let nextToken: string | undefined;
do {
const { results, nextToken: token, hasNextPage } = await list({
prefix: 'photos/',
options: {
pageSize: 20,
nextToken
}
});
console.log('Page results:', results);
nextToken = hasNextPage ? token : undefined;
} while (nextToken);
// List directories (using delimiter)
const { results: directories } = await list({
prefix: 'docs/',
options: {
delimiter: '/',
listAll: true
}
});Delete objects from storage.
/**
* Remove objects from storage
* @param input - Remove configuration
* @returns Promise with removal results
*/
function remove(input: RemoveInput): Promise<RemoveOutput>;
interface RemoveInput {
key: string | string[];
options?: {
accessLevel?: 'guest' | 'protected' | 'private';
};
}
interface RemoveOutput {
deleted: string[];
errors?: Array<{
key: string;
message: string;
}>;
}Usage Examples:
import { remove } from "aws-amplify/storage";
// Remove single object
const { deleted } = await remove({
key: 'uploads/old-file.txt',
options: {
accessLevel: 'private'
}
});
// Remove multiple objects
const { deleted, errors } = await remove({
key: [
'temp/file1.txt',
'temp/file2.txt',
'temp/file3.txt'
]
});
console.log('Deleted files:', deleted);
if (errors) {
console.log('Errors:', errors);
}Copy objects within storage.
/**
* Copy objects in storage
* @param input - Copy configuration
* @returns Promise with copy result
*/
function copy(input: CopyInput): Promise<CopyOutput>;
interface CopyInput {
source: {
key: string;
accessLevel?: 'guest' | 'protected' | 'private';
targetIdentityId?: string;
};
destination: {
key: string;
accessLevel?: 'guest' | 'protected' | 'private';
};
}
interface CopyOutput {
key: string;
}Usage Example:
import { copy } from "aws-amplify/storage";
const { key } = await copy({
source: {
key: 'originals/photo.jpg',
accessLevel: 'private'
},
destination: {
key: 'backups/photo-backup.jpg',
accessLevel: 'private'
}
});
console.log('File copied to:', key);Get metadata and properties of objects.
/**
* Get object properties and metadata
* @param input - Properties request configuration
* @returns Promise with object properties
*/
function getProperties(input: GetPropertiesInput): Promise<GetPropertiesOutput>;
interface GetPropertiesInput {
key: string;
options?: {
accessLevel?: 'guest' | 'protected' | 'private';
targetIdentityId?: string;
};
}
interface GetPropertiesOutput {
key: string;
contentType?: string;
contentLength?: number;
eTag?: string;
lastModified?: Date;
metadata?: Record<string, string>;
versionId?: string;
}Usage Example:
import { getProperties } from "aws-amplify/storage";
const properties = await getProperties({
key: 'documents/report.pdf',
options: {
accessLevel: 'private'
}
});
console.log('File size:', properties.contentLength);
console.log('Content type:', properties.contentType);
console.log('Last modified:', properties.lastModified);
console.log('Metadata:', properties.metadata);Generate signed URLs for secure access to objects.
/**
* Get a signed URL for object access
* @param input - URL generation configuration
* @returns Promise with signed URL
*/
function getUrl(input: GetUrlInput): Promise<GetUrlOutput>;
interface GetUrlInput {
key: string;
options?: {
accessLevel?: 'guest' | 'protected' | 'private';
targetIdentityId?: string;
expiresIn?: number; // seconds
validateObjectExistence?: boolean;
useAccelerateEndpoint?: boolean;
};
}
interface GetUrlOutput {
url: URL;
expiresAt: Date;
}Usage Examples:
import { getUrl } from "aws-amplify/storage";
// Get URL for download
const { url, expiresAt } = await getUrl({
key: 'photos/vacation.jpg',
options: {
accessLevel: 'private',
expiresIn: 3600 // 1 hour
}
});
console.log('Download URL:', url.toString());
console.log('Expires at:', expiresAt);
// Use URL in img tag
const img = document.createElement('img');
img.src = url.toString();
// Get URL with validation
const { url: validatedUrl } = await getUrl({
key: 'documents/file.pdf',
options: {
validateObjectExistence: true,
expiresIn: 300 // 5 minutes
}
});Control object access permissions with access levels.
// Public access (anyone can read)
await uploadData({
key: 'public/announcement.txt',
data: 'Public announcement',
options: {
accessLevel: 'guest'
}
});
// Protected access (readable by all users, writable by owner)
await uploadData({
key: 'profiles/user-avatar.jpg',
data: avatarFile,
options: {
accessLevel: 'protected'
}
});
// Private access (only accessible by owner)
await uploadData({
key: 'private/personal-document.pdf',
data: documentFile,
options: {
accessLevel: 'private'
}
});Storage operations in server environments.
// Available from "aws-amplify/storage/server"
import {
uploadData, downloadData, list, remove
} from "aws-amplify/storage/server";
// Usage is identical to client-side, but runs in server context
// Requires proper server-side Amplify configuration// Storage configuration
interface StorageConfig {
S3?: {
bucket?: string;
region?: string;
dangerouslyConnectToHttpEndpointForTesting?: boolean;
customEndpoint?: string;
};
}
// Transfer states
type TransferState = 'NOT_STARTED' | 'IN_PROGRESS' | 'PAUSED' | 'CANCELLED' | 'SUCCESS' | 'ERROR';
// Error types
class StorageError extends Error {
name: 'StorageError';
message: string;
cause?: Error;
}
class StorageValidationError extends StorageError {
name: 'StorageValidationError';
}Storage operations can throw various errors:
import { uploadData, StorageError } from "aws-amplify/storage";
try {
const upload = uploadData({
key: 'test-file.txt',
data: 'test content'
});
await upload.result;
} catch (error) {
if (error instanceof StorageError) {
switch (error.name) {
case 'NoCredentials':
console.log('Authentication required');
break;
case 'Forbidden':
console.log('Access denied');
break;
case 'NotFound':
console.log('Object not found');
break;
default:
console.log('Storage error:', error.message);
break;
}
} else {
console.log('Unexpected error:', error);
}
}uploads/, avatars/, documents/)private for sensitive data)