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
Answer a question...

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