0

I am trying to upload to an s3 bucket in next and have a couple of errors

I am using the package: https://www.npmjs.com/package/@aws-sdk/client-s3

My Controller is:

@Post('test-doc')
    @UseInterceptors(FileInterceptor('file'))
    async testDocument(@UploadedFile() file: Express.Multer.File) {
        return this.assetService.upload(file);
    }

With my service:

async upload(file) {
    return await uploadObject(file, 'SpacePlus', file.originalname);
  }

And my functions which work with are ok with a helloworld text file create:

import {PutObjectCommand, S3Client} from "@aws-sdk/client-s3";
import {Logger} from "@nestjs/common";



// Validate the request and directs to the spaces endpoint
const s3Client = new S3Client({
    endpoint: "",
    forcePathStyle: false,
    region: 'us-east-1',
    credentials: {
        accessKeyId: '',
        secretAccessKey: ''
    }
});

//Function to upload
const uploadObject = async (file, bucket, name) => {
    // Define the params
    const params = {
        Bucket: bucket,
        Key: "staging/" + String(name),
        Body: file,
    }
    try {
        const data = await s3Client.send(new PutObjectCommand(params));
        Logger.log(
            "Successfully uploaded object: " +
            params.Bucket +
            "/" +
            params.Key
        );
        return data
        }
        catch (err)
        {
            console.log("Error", err)
        }
    }

export default uploadObject;

So the error is

TypeError: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received an instance of Object

And if I cast the file object to an array I get the this error:

Error MissingContentLength: UnknownError

So Im a little stuck on where to go next to get this working

Graham Morby
  • 123
  • 2
  • 11

3 Answers3

1
async upload(file) {
return await uploadObject(file, 'SpacePlus', file.originalname);
}

file which you are sending must be Buffer

const file = event.target.files[0]
                const reader = new window.FileReader()
                reader.readAsArrayBuffer(file)
            
                reader.onloadend = () => {
                bufferFile = Buffer(reader.result)

try to get the buffer of file to be uploaded like code snippet in react.

1

You can send buffer instead of the file directly in the body in the uploadObject method as it is expecting buffer not instance of an object as pointed out in the error. You can desconstruct the file by using

{buffer} = file 

instead and send the buffer here.

{buffer} = file
    const params = {
        Bucket: bucket,
        Key: "staging/" + String(name),
        Body: buffer,
    }
0

I updated the controller to send the buffer

 @Post('test-doc')
    @UseInterceptors(FileInterceptor('file'))
    async testDocument(@UploadedFile() file: Express.Multer.File) {
        return this.assetService.upload(file, file.buffer);
    }
Graham Morby
  • 123
  • 2
  • 11