S3 File Upload
Anyone got an idea what I am missing here:
And this is my api route:
But my req.body keeps returning undefined, any ideas?
I am using the v3 package:
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { randomUUID } from 'crypto';
import type { NextApiRequest, NextApiResponse } from 'next';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
const accountid = process.env.CLOUDFLARE_ACCOUNT_ID
const s3 = new S3Client({
endpoint: `https://${accountid}.r2.cloudflarestorage.com`,
region: process.env.R2_REGION,
credentials: {
accessKeyId: process.env.WRITE_CLOUDFLARE_R2_ACCESS_KEY_ID!,
secretAccessKey: process.env.WRITE_CLOUDFLARE_R2_SECRET_ACCESS_KEY!,
}
})
// Check if the file is present in the request body
if (!req.body || !req.body.file) {
throw new Error('No file data found in the request');
}
console.log("api file upload", req.body.file)
// Get the file content and filename from the request
const file = req.body.file; // Assuming the uploaded file is in a 'file' field in the form-data
const fileContent = file.buffer;
const filename = file.name;
const uniqueName = `${randomUUID()}-${filename}`
const conditions = [['content-length-range', 0, 10485760]]
// Prepare the parameters for the S3 PutObjectCommand
const params = {
Bucket: 'test',
Key: uniqueName,
Body: fileContent,
};
const command = new PutObjectCommand(params);
await s3.send(command);
res.status(200).json({ message: 'File uploaded successfully' });
} catch (error) {
console.error('Error uploading file to S3:', error);
res.status(500).json({ message: 'Error uploading file to S3' });
}
}
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { randomUUID } from 'crypto';
import type { NextApiRequest, NextApiResponse } from 'next';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
const accountid = process.env.CLOUDFLARE_ACCOUNT_ID
const s3 = new S3Client({
endpoint: `https://${accountid}.r2.cloudflarestorage.com`,
region: process.env.R2_REGION,
credentials: {
accessKeyId: process.env.WRITE_CLOUDFLARE_R2_ACCESS_KEY_ID!,
secretAccessKey: process.env.WRITE_CLOUDFLARE_R2_SECRET_ACCESS_KEY!,
}
})
// Check if the file is present in the request body
if (!req.body || !req.body.file) {
throw new Error('No file data found in the request');
}
console.log("api file upload", req.body.file)
// Get the file content and filename from the request
const file = req.body.file; // Assuming the uploaded file is in a 'file' field in the form-data
const fileContent = file.buffer;
const filename = file.name;
const uniqueName = `${randomUUID()}-${filename}`
const conditions = [['content-length-range', 0, 10485760]]
// Prepare the parameters for the S3 PutObjectCommand
const params = {
Bucket: 'test',
Key: uniqueName,
Body: fileContent,
};
const command = new PutObjectCommand(params);
await s3.send(command);
res.status(200).json({ message: 'File uploaded successfully' });
} catch (error) {
console.error('Error uploading file to S3:', error);
res.status(500).json({ message: 'Error uploading file to S3' });
}
}
aws-sdk/client-s3
2 Replies
This is the frontend:
const handleFileUpload = async (
event: React.ChangeEvent<HTMLInputElement>
) => {
if (!event.target.files) return;
const file = event.target.files[0];
if (!file) {
throw new Error("No file selected");
}
const formData = new FormData();
try {
const response = await fetch("/api/s3/upload", {
method: "POST",
body: formData,
headers: { "Content-Type": "multipart/form-data" },
});
if (response.ok) {
console.log("File uploaded successfully");
} else {
console.error("Error uploading file:", response.statusText);
}
} catch (error) {
console.error("Error uploading file:", error);
}
};
<label htmlFor="fileInput">Select a file:</label>
<input
type="file"
id="fileInput"
onChange={handleFileUpload}
/>
const handleFileUpload = async (
event: React.ChangeEvent<HTMLInputElement>
) => {
if (!event.target.files) return;
const file = event.target.files[0];
if (!file) {
throw new Error("No file selected");
}
const formData = new FormData();
try {
const response = await fetch("/api/s3/upload", {
method: "POST",
body: formData,
headers: { "Content-Type": "multipart/form-data" },
});
if (response.ok) {
console.log("File uploaded successfully");
} else {
console.error("Error uploading file:", response.statusText);
}
} catch (error) {
console.error("Error uploading file:", error);
}
};
<label htmlFor="fileInput">Select a file:</label>
<input
type="file"
id="fileInput"
onChange={handleFileUpload}
/>
Are you adding the file to
FormData
anywhere?
const formData = new FormData()
formData.append('file', file)
const formData = new FormData()
formData.append('file', file)