'Uploading multi sheet `.xls` file to AWS S3 using AWS lambda
I am creating a multi sheet .xls file in AWS lambda and pushing it to S3 Bucket. On testing the file creation in local, the file is as expected and can be opened.
When I pull the file that is loaded to S3 I am getting the following error, trying to open the file in MS excel.
The file format and extension of don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway? s3 xlsx
I can still open the file but can't edit that file.
Following is the code I used to push the file to S3. The error seems to be with the content type. I am wondering what is the correct content type to be used.
const file = await this.loadFile('test.xls', '/tmp');
const input = {
Bucket: BUCKET_NAME,
Key: 'output/test.xls',
Body: file,
ContentType: 'application/vnd.ms-excel'
};
await client.putObject(input);
Solution 1:[1]
This might not be what you want, but using Buffer.from(file, "binary") will work when uploading files of any types to S3 buckets.
Here is my snippet:
var AWS = require("aws-sdk");
// Set region
AWS.config.update({ region: "your-region" });
var s3 = new AWS.S3({ apiVersion: "2006-03-01" });
var fs = require("fs");
// Set bucket name
const bucket = "my-bucket";
const file = "test.xlsx";
fs.readFile(file, function (err, data) {
if (err) console.log(err);
const fileContent = Buffer.from(file, "binary");
s3.putObject(
{
Bucket: bucket,
Key: file,
Body: fileContent,
},
function (resp) {
console.log(arguments);
console.log("Successfully uploaded, ", file);
}
);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | shimo |
