I'm having trouble uploading an image to Digital Ocean Spaces.
Here is my client-side code:
const formData = new FormData();
formData.append('myFile', file as string)
fetch('/api/upload',
{
method: 'POST',
body: formData
}).then(response => {
console.log(`response sucess: ${response.status}`)
}).catch(error => {
console.log(error)
// Handle error
});
As for the server-side code (Next.js), I must admit I am a bit confused..
export default async function upload(req: NextApiRequest & { [key: string]: any }, res: NextApiResponse) {
const multerUpload = multer({ dest: "uploads/" });
await runMiddleware(req, res, multerUpload.single("file"));
const file = req.body.myFile;
const { bucket, key, fileName } = req.body;
const contentHash = crypto.createHash('sha256').update(file).digest('hex');
const content_length = getBytesForContentLength(file)
const bucketParams = {
Bucket: bucket,
Key: key,
Body: file,
ContentType: getImageType(file),
ContentLength: content_length,
Headers: {
'X-Amz-Content-SHA256': `hex(${contentHash})`
}
};
try {
const response = await s3Client.send(new PutObjectCommand(bucketParams));
console.log(response.$metadata);
console.log("Success");
//todo: if successful, post the path to the server DB
res.status(200)
} catch (err) {
console.log("Error", err);
res.status(500).send("Server Error");
}
The mentioned functions are defined as follows:
function runMiddleware(req: NextApiRequest & {[key: string]: any}, res: NextApiResponse, fn: (...args: any[]) => void): Promise<any> {
return new Promise((resolve, reject) => {
fn(req, res, (result: any) => {
if (result instanceof Error) {
return reject(result);
}
return resolve(result);
});
});
}
export const config = {
api: {
bodyParser: false,
},
};
and
function getBytesForContentLength(base64String: string): number {
// assume that file_str is the base64 encoded file string
const myBuffer = Buffer.from(base64String, 'base64');
return myBuffer.byteLength
}
The error message I'm encountering reads as follows:
'$fault': 'client',
'$metadata': {
httpStatusCode: 400,
requestId: '***',
extendedRequestId: undefined,
cfId: undefined,
attempts: 1,
totalRetryDelay: 0
},
Code: 'XAmzContentSHA256Mismatch',
BucketName: '***',
RequestId: '***',
HostId: '***'
}
The XAmzContentSHA256Mismatch error seems persistent despite my attempt to manually set the X-Amz-Content header. Additionally, specifying the ContentLength parameter is crucial to avoid another error related to ContentLength.
Code: 'MissingContentLength',
BucketName: '***',
RequestId: '***',
HostId: '***'
I would greatly appreciate any assistance in resolving these issues.