|
| 1 | +# File Downloads |
| 2 | + |
| 3 | +The `Send.file()` method creates download responses from files on the filesystem. |
| 4 | + |
| 5 | +## Basic Usage |
| 6 | + |
| 7 | +```typescript |
| 8 | +import { Send } from '@neabyte/deserve' |
| 9 | + |
| 10 | +export async function GET(req: Request): Response { |
| 11 | + return await Send.file('./uploads/document.pdf', 'monthly-report.pdf') |
| 12 | +} |
| 13 | +``` |
| 14 | + |
| 15 | +## With Absolute Paths |
| 16 | + |
| 17 | +```typescript |
| 18 | +export async function GET(req: Request): Response { |
| 19 | + return await Send.file(`${Deno.cwd()}/downloads/sample.txt`, 'hello-world.txt') |
| 20 | +} |
| 21 | +``` |
| 22 | + |
| 23 | +## Auto-Generated Filename |
| 24 | + |
| 25 | +```typescript |
| 26 | +export async function GET(req: Request): Response { |
| 27 | + // Filename will be extracted from the file path |
| 28 | + return await Send.file('./uploads/report.pdf') |
| 29 | +} |
| 30 | +``` |
| 31 | + |
| 32 | +## With Custom Headers |
| 33 | + |
| 34 | +```typescript |
| 35 | +export async function GET(req: Request): Response { |
| 36 | + return await Send.file( |
| 37 | + './uploads/document.pdf', |
| 38 | + 'custom-name.pdf', |
| 39 | + { |
| 40 | + headers: { |
| 41 | + 'Cache-Control': 'public, max-age=3600', |
| 42 | + 'X-Custom-Header': 'value' |
| 43 | + } |
| 44 | + } |
| 45 | + ) |
| 46 | +} |
| 47 | +``` |
| 48 | + |
| 49 | +## Dynamic File Downloads |
| 50 | + |
| 51 | +```typescript |
| 52 | +// routes/downloads/[filename].ts |
| 53 | +export async function GET(req: Request, params: Record<string, string>): Response { |
| 54 | + const { filename } = params |
| 55 | + // Validate filename to prevent directory traversal |
| 56 | + if (filename.includes('..') || filename.includes('/')) { |
| 57 | + return Send.json({ error: 'Invalid filename' }, { status: 400 }) |
| 58 | + } |
| 59 | + try { |
| 60 | + return await Send.file(`${Deno.cwd()}/downloads/${filename}`) |
| 61 | + } catch (error) { |
| 62 | + return Send.json({ error: 'File not found' }, { status: 404 }) |
| 63 | + } |
| 64 | +} |
| 65 | +``` |
| 66 | + |
| 67 | +## File Type Detection |
| 68 | + |
| 69 | +```typescript |
| 70 | +export async function GET(req: Request): Response { |
| 71 | + const url = new URL(req.url) |
| 72 | + const fileType = url.searchParams.get('type') || 'pdf' |
| 73 | + const fileMap = { |
| 74 | + pdf: './uploads/document.pdf', |
| 75 | + doc: './uploads/document.doc', |
| 76 | + txt: './uploads/document.txt' |
| 77 | + } |
| 78 | + const filePath = fileMap[fileType as keyof typeof fileMap] |
| 79 | + if (!filePath) { |
| 80 | + return Send.json({ error: 'Unsupported file type' }, { status: 400 }) |
| 81 | + } |
| 82 | + return await Send.file(filePath, `document.${fileType}`) |
| 83 | +} |
| 84 | +``` |
| 85 | + |
| 86 | +## Error Handling |
| 87 | + |
| 88 | +```typescript |
| 89 | +export async function GET(req: Request): Response { |
| 90 | + try { |
| 91 | + return await Send.file('./uploads/document.pdf', 'report.pdf') |
| 92 | + } catch (error) { |
| 93 | + return Send.json( |
| 94 | + { error: 'File not found or cannot be read' }, |
| 95 | + { status: 404 } |
| 96 | + ) |
| 97 | + } |
| 98 | +} |
| 99 | +``` |
| 100 | + |
| 101 | +## Multiple File Types |
| 102 | + |
| 103 | +```typescript |
| 104 | +export async function GET(req: Request): Response { |
| 105 | + const url = new URL(req.url) |
| 106 | + const format = url.searchParams.get('format') || 'pdf' |
| 107 | + const files = { |
| 108 | + pdf: './reports/monthly-report.pdf', |
| 109 | + excel: './reports/monthly-report.xlsx', |
| 110 | + csv: './reports/monthly-report.csv' |
| 111 | + } |
| 112 | + const filePath = files[format as keyof typeof files] |
| 113 | + if (!filePath) { |
| 114 | + return Send.json({ error: 'Unsupported format' }, { status: 400 }) |
| 115 | + } |
| 116 | + return await Send.file(filePath, `monthly-report.${format}`) |
| 117 | +} |
| 118 | +``` |
| 119 | + |
| 120 | +## When to Use File Downloads |
| 121 | + |
| 122 | +- **Static files** - Documents, images, archives |
| 123 | +- **User uploads** - Files uploaded by users |
| 124 | +- **Generated reports** - PDF reports, Excel files |
| 125 | +- **Media files** - Images, videos, audio |
| 126 | +- **Backup files** - Database dumps, configuration files |
| 127 | + |
| 128 | +## Parameters |
| 129 | + |
| 130 | +- `filePath` - Path to the file on the filesystem |
| 131 | +- `filename` - Optional custom filename for download (defaults to file basename) |
| 132 | +- `options` - Additional ResponseInit options (optional) |
| 133 | + |
| 134 | +## Security Considerations |
| 135 | + |
| 136 | +- **Validate file paths** - Prevent directory traversal attacks |
| 137 | +- **Check file permissions** - Ensure files are readable |
| 138 | +- **Sanitize filenames** - Remove dangerous characters |
| 139 | +- **Use absolute paths** - Avoid relative path confusion |
| 140 | + |
| 141 | +## Example Security Implementation |
| 142 | + |
| 143 | +```typescript |
| 144 | +export async function GET(req: Request, params: Record<string, string>): Response { |
| 145 | + const { filename } = params |
| 146 | + // Security checks |
| 147 | + if (!filename || filename.includes('..') || filename.includes('/')) { |
| 148 | + return Send.json({ error: 'Invalid filename' }, { status: 400 }) |
| 149 | + } |
| 150 | + // Only allow specific file extensions |
| 151 | + const allowedExtensions = ['.pdf', '.txt', '.jpg', '.png'] |
| 152 | + const hasValidExtension = allowedExtensions.some(ext => filename.endsWith(ext)) |
| 153 | + if (!hasValidExtension) { |
| 154 | + return Send.json({ error: 'File type not allowed' }, { status: 400 }) |
| 155 | + } |
| 156 | + try { |
| 157 | + return await Send.file(`${Deno.cwd()}/downloads/${filename}`) |
| 158 | + } catch (error) { |
| 159 | + return Send.json({ error: 'File not found' }, { status: 404 }) |
| 160 | + } |
| 161 | +} |
| 162 | +``` |
| 163 | + |
| 164 | +## Next Steps |
| 165 | + |
| 166 | +- [JSON Responses](/response/json) - Structured data responses |
| 167 | +- [Text Responses](/response/text) - Plain text responses |
| 168 | +- [Static File Serving](/static-file/basic) - Serve static files |
0 commit comments