EDMS/server/api/dms/upload-file.post.js
shb 40cf8ebab5 Added file upload functionality
Backend works when trying to use Postman to request the API endpoint. File upload in the frontend also works since the data is parsed properly as multi-part form data. The issue is the frontend seems to cannot directly send request to backend and is outright rejected.
2025-06-16 14:29:33 +08:00

83 lines
2.3 KiB
JavaScript

import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; // ES Modules import
import { readMultipartFormData } from 'h3';
export default defineEventHandler(async (event) => {
const parts = [];
// Allow headers for specific origins
// setHeader(event, 'Access-Control-Allow-Origin', 'http://localhost:3000');
// setHeader(event, 'Access-Control-Allow-Methods', 'POST, OPTIONS');
// setHeader(event, 'Access-Control-Allow-Headers', 'Content-Type');
if (event.method === 'OPTIONS') {
return new Response(null, { status: 204 });
}
try {
const parts = await readMultipartFormData(event, { maxSize: 20 * 1024 * 1024});
if (!parts) {
return {
status: 400,
message: "Bad request. No parts found."
}
}
} catch (error) {
console.error('Failed to read multi-part data:', error);
return {
status: 500,
message: "Failed to read multi-part data"
}
}
console.log("Hello from the backend!");
const S3_Config = {
region: process.env.NUXT_AWS_REGION,
credentials: {
accessKeyId: process.env.NUXT_AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.NUXT_AWS_SECRET_ACCESS_KEY
}
}
// Create S3 client with config
const client = new S3Client(S3_Config);
// const { fileName, file } = await readMultipartFormData(event);
const fileNamePart = parts.find(p => p.name === "fileName");
const filePart = parts.find(p => p.name === "file");
if (!fileNamePart || !filePart) {
return {
status: 400,
message: "Missing required fields { fileName, file }"
}
}
const fileName = fileNamePart.data.toString();
const file = filePart.data;
const input = {
Bucket: process.env.NUXT_AWS_BUCKET,
Key: fileName,
Body: file,
ContentType: filePart.type
}
const command = new PutObjectCommand(input);
try {
const response = await client.send(command);
console.log(response);
return response;
} catch (error) {
console.error(error);
return {
status: 500,
message: "Failed to upload file to S3",
error: error
}
}
})