I uploaded and .xlsx
into my Amazon S3 Bucket
. The problem is when i am trying to retrieve it , the file is corrupted
when i try to open it with Microsoft Excel
. I am using AWS SDK
for .NET
.
The logic of downloading the file from the bucket :
public async Task<Stream?> DownloadFile(string s3Key)
{
try
{
var getFile = new GetObjectRequest
{
BucketName = _bucketName,
Key = s3Key
};
var response = await AmazonS3Client.GetObjectAsync(getFile);
return response.ResponseStream;
}
catch (AmazonS3Exception e)
{
Console.WriteLine(e);
return null;
}
}
Than goes into my BUCKET SERVICE Layer
public async Task<Stream?> DownloadFile(string s3Key)
{
var getFileStream = await _bucketAcces.DownloadFile(s3Key);
return getFileStream;
}
Than into my ADMIN SERVICE LAYER:
public Task<Stream?> GetExcelFile()
{
return _bucketService.DownloadFile("produseExcelExample.xlsx");
}
Than into my controller:
public async Task<IActionResult> GetExcelFile()
{
var fileStream = await _adminService.GetExcelFile();
if (fileStream is not null)
{
var fileMemoryStream = new MemoryStream();
await fileStream.CopyToAsync(fileMemoryStream);
fileMemoryStream.Position = 0;
var fileStreamResult = new FileStreamResult(fileMemoryStream,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
FileDownloadName = "Exemplu_excel.xlsx"
};
return fileStreamResult;
}
return NotFound("Error on downloading file");
}
The file gets downloaded , everything is fine , but when i try to open it i get the corrupted file error:
And then
UPDATE
This is how i receive it on the frontend(forgot to mention this):
const downloadExcel = async () => {
try {
// Call the admin service to get the file
const response = await adminService.downloadExcel();
// Convert the response into a Blob (binary large object)
const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
// Create a URL for the blob object
const url = window.URL.createObjectURL(blob);
// Create an anchor element and set the href to the blob URL
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'exemplu_fisier.xlsx'); // Set the desired file name
// Programmatically click the anchor to trigger the download
document.body.appendChild(link);
link.click();
// Clean up by removing the anchor and revoking the object URL
link.remove();
window.URL.revokeObjectURL(url);
} catch (error) {
fireAlarm(showErrorFileDwonload);
console.error("Error downloading Excel file:", error);
}
}
I’m, using Vue.js 3 for the frontend
UPDATE 2
It has 10.77kB and the file i am downloading has 16.77kB
. So something is not good when i retrieve it from the bucket, that s why it might be corrupted.
What to do here ?
UPDATE SOLVED
Such a rookie mistake i made. Of course the file was treated as JSON
not Blob
. Forgot to put blob
in my responseType
on the API request to the backend.
4