I am uploading an image to aws-s3 with the aws-sdk. The image seems to be sucessfully written to my bucket but, when I download the image through the aws dashboard or using GetObjectCommand, the image seems to be corrupted somehow. My instinct here is that this is some sort of encoding issue having looked at both files with VSCode's hex editor but I'm really stuck. Here's my code for doing the upload:
export const client = new S3Client({
region: "eu-north-1",
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
},
});
export function handleGetObjectError(err, res) {
if (err.Code == "NoSuchKey") {
res.status(404);
res.send("The referenced image does not exist");
} else {
console.log(err);
res.status(500);
res.send("Error fetching from aws");
}
}
export async function uploadFileToAWS(file, key) {
const input = {
Body: file,
Bucket: process.env.S3_BUCKET,
Key: key,
ContentEncoding: "utf-8",
};
const command = new PutObjectCommand(input);
return client.send(command);
}
export function upload_image(request, response) {
let uuid = uuidv4().toString();
var filename = "";
var storage = multer.diskStorage({
// maybe change this to memory storage as it may be quicker
destination: function (request, file, callback) {
callback(null, "./temp");
},
filename: function (request, file, callback) {
var temp_file_arr = file.originalname.split(".");
var temp_file_extension = temp_file_arr[temp_file_arr.length - 1];
filename = uuid + "." + temp_file_extension;
callback(null, filename);
},
});
var upload = multer({ storage: storage }).single("image");
upload(request, response, function (error) {
if (error) {
response.status(500);
console.log(error);
response.send("Error Uploading File");
} else {
console.log(filename);
fs.readFile("./temp/" + filename, "utf-8", (error, f) => {
if (error) {
response.status(500);
console.log(error);
response.send("Error Uploading File");
return;
}
uploadFileToAWS(f, filename).then((awsRes) => {
// should probably clean up the temp file here
response.status(201);
response.send(filename);
});
});
}
});
}
I've tried setting different encodings for both the fs read and the ContentEncoding field but this doesn't appear to make any difference