Question

File being created, but file size is 0 bytes (Spaces API Upload File)

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!


Submit an answer


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!

Sign In or Sign Up to Answer

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.

KFSys
Site Moderator
Site Moderator badge
April 6, 2023

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 the Body parameter of your uploadObject() function. This will read the contents of the file and upload them to DigitalOcean Spaces.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

card icon
Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Sign up
card icon
Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We’d like to help.

Learn more
card icon
Become a contributor

You get paid; we donate to tech nonprofits.

Learn more
Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow – whether you’re running one virtual machine or ten thousand.

Learn more ->
DigitalOcean Cloud Control Panel
Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.

This promotional offer applies to new account only.

© 2023 DigitalOcean, LLC.