Hey everyone,
Been banging my head against the wall for a few days trying to get this issue sorted, and I can’t quite figure it out.
Technology: NodeJS
Task: Create a simple backend server that will accept a form with file uploads, and that file will be upstreamed to DO Spaces bucket.
Issue: When testing API route with Postman or the NextJS frontend, request comes back as successful, file is uploaded to bucket, except that the file has a size of 0 bytes. File name is successfully passed, however.
import express from 'express';
import dotenv from 'dotenv';
import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
import formidable from 'formidable';
import fs from 'fs';
import cors from 'cors';
dotenv.config();
_const_ app = express();
app.use(express.json());
app.use(cors())
_const_ s3Client = new __S3Client__({
endpoint: process.env.DO_SPACES_URL || "https://nyc3.digitaloceanspaces.com",
forcePathStyle: false,
region: "nyc3",
credentials: {
accessKeyId: process.env.DO_SPACES_ID,
secretAccessKey: process.env.DO_SPACES_SECRET
}
});
_const_ uploadObject = _async_ ({ _Key_, _Body_, _ACL_, _Metadata_ }) _=>_ {
_const_ params = { Bucket: process.env.DO_SPACES_BUCKET, Key, Body, ACL, Metadata };
try {
_const_ data = await s3Client.send(new __PutObjectCommand__(params));
console.log(`Successfully uploaded object: ${params.Bucket}/${params.Key}`);
return data;
} catch (err) {
console.log("Error", err);
}
};
app.post('/submit-form', (_req_, _res_) _=>_ {
_const_ form = formidable()
form.parse(_req_, _async_ (_err_, _fields_, _files_) _=>_ {
if (!_files_) {
_res_.status(400).json({ error: 'No file uploaded' });
return
}
try {
_const_ file = _files_.file;
return uploadObject({
Key: file.originalFilename,
Body: __fs__.originalFilename,
ACL: 'public-read',
Metadata: { },
}),
_res_.status(201).send('File uploaded successfully');
}
catch (err) {
console.log(err)
_res_.status(500).json({ error: 'Failed to upload file' });
}
})
});
app.listen(3001, () _=>_ {
console.log('Server listening on port 3001.');
});
I’m really at a loss, and if anyone could shed some light on the issue I’d be eternally grateful.
Thanks in advance!
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.
This promotional offer applies to new account only.
Hey @1169e79adbc0419f85b59cf8302269,
It looks like there is an issue in the code where you’re trying to upload the file to DigitalOcean Spaces . Specifically, you’re passing
__fs__.originalFilename
as the file content, which is actually just the filename and not the contents of the file.To fix this issue, you can replace
__fs__.originalFilename
with__fs__.createReadStream(file.path)
in theBody
parameter of youruploadObject()
function. This will read the contents of the file and upload them to DigitalOcean Spaces.