You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET通过AWS SDK从S3下载的Excel文件损坏问题及解决

Excel文件从S3下载后打开提示损坏的问题排查与解决

问题概述

将.xlsx文件上传至Amazon S3 Bucket后,通过AWS SDK for .NET实现的后端接口下载文件,文件可正常触发下载,但用Microsoft Excel打开时提示文件损坏。

后端下载逻辑代码

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;
    }
}

Bucket服务层

public async Task<Stream?> DownloadFile(string s3Key)
{
    var getFileStream = await _bucketAcces.DownloadFile(s3Key);
    return getFileStream;
}

Admin服务层

public Task<Stream?> GetExcelFile()
{
    return _bucketService.DownloadFile("produseExcelExample.xlsx");
}

控制器代码

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");
}

前端下载代码(Vue.js 3)

const downloadExcel = async () => {
    try {
        const response =  await adminService.downloadExcel();
        
        const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'exemplu_fisier.xlsx');

        document.body.appendChild(link);
        link.click();

        link.remove();
        window.URL.revokeObjectURL(url);
    } catch (error) {
        fireAlarm(showErrorFileDwonload);
        console.error("Error downloading Excel file:", error);
    }
}

排查过程

对比S3存储的原文件与下载后的文件大小:原文件为10.77kB,下载后的文件为16.77kB,文件体积明显增大,说明文件内容在传输过程中被篡改。进一步排查发现,前端API请求未设置responseType为blob,导致二进制文件被默认当作JSON格式解析,破坏了文件的二进制结构,最终导致文件损坏。

解决方法

在前端发起API请求时,必须明确设置responseType为blob,确保二进制文件以原始格式接收。例如,若使用Axios发送请求,需修改请求配置:

// 示例:修改adminService.downloadExcel的实现
const downloadExcel = () => {
    return axios.get('/api/admin/get-excel-file', {
        responseType: 'blob' // 关键配置
    });
}

修改后,前端接收到正确的二进制数据,转换为Blob后生成的文件可正常被Microsoft Excel打开。

内容的提问来源于stack exchange,提问作者Misu Stefan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 01:37:22