FileContentResult返回Excel文件损坏

发布于 2025-01-29 22:45:01 字数 2011 浏览 3 评论 0原文

我正在尝试从FTP下载XLSX文件,但是当我下载并尝试打开它时,我会发现它是一个损坏的文件。 。我共享背部和前代码。

public async Task<TransacResult> DownloadFileInterface(Uri serverUri, string fileName)
    {
        StreamReader sr;
        byte[] fileContent;
        try
        {
            string ftpUser = GetConfiguration()["SuatKeys:FTPSuatUser"];
            string ftpPassword = GetConfiguration()["SuatKeys:FTPSuatPassword"];

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
            request.Method = WebRequestMethods.Ftp.DownloadFile;
            request.KeepAlive = false;
            request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
            sr = new StreamReader(request.GetResponse().GetResponseStream());
            fileContent = Encoding.UTF8.GetBytes(sr.ReadToEnd());
            sr.Close();
            sr.Dispose();
            FtpWebResponse response = (FtpWebResponse)await request.GetResponseAsync();
            var fileContentResult = new FileContentResult(fileContent, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = fileName + ".xlsx"
            };
            return new TransacResult(true, fileContentResult);
        }
        catch (Exception ex)
        {
            return new TransacResult(false, new Message("SUAT-ERR-C02", MessageCategory.Error, "Conexión rechazada", ex.Message));
        }
    }

async downloadlayout() {
    var obj = this.interfaces.item;
    if (this.$store.state.usuarioActivo.modeD == 0)
      obj = serialize(obj);
    const res = await this.$store.dispatch("apiPost", {
      url: "Interface/DownloadDinamycLayout",
      item: obj
    })
    console.clear();
    console.log(res);
    const a = document.createElement("a"); 
    a.href = "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64," + res.fileContents; 
    a.download = res.fileDownloadName;
    a.click(); 
    a.remove();
},

读取文件没有任何问题 问候

I am trying to download an xlsx file from an ftp but when I download and try to open it I get that it is a corrupt file. . I share the back and front code.

public async Task<TransacResult> DownloadFileInterface(Uri serverUri, string fileName)
    {
        StreamReader sr;
        byte[] fileContent;
        try
        {
            string ftpUser = GetConfiguration()["SuatKeys:FTPSuatUser"];
            string ftpPassword = GetConfiguration()["SuatKeys:FTPSuatPassword"];

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
            request.Method = WebRequestMethods.Ftp.DownloadFile;
            request.KeepAlive = false;
            request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
            sr = new StreamReader(request.GetResponse().GetResponseStream());
            fileContent = Encoding.UTF8.GetBytes(sr.ReadToEnd());
            sr.Close();
            sr.Dispose();
            FtpWebResponse response = (FtpWebResponse)await request.GetResponseAsync();
            var fileContentResult = new FileContentResult(fileContent, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = fileName + ".xlsx"
            };
            return new TransacResult(true, fileContentResult);
        }
        catch (Exception ex)
        {
            return new TransacResult(false, new Message("SUAT-ERR-C02", MessageCategory.Error, "Conexión rechazada", ex.Message));
        }
    }

async downloadlayout() {
    var obj = this.interfaces.item;
    if (this.$store.state.usuarioActivo.modeD == 0)
      obj = serialize(obj);
    const res = await this.$store.dispatch("apiPost", {
      url: "Interface/DownloadDinamycLayout",
      item: obj
    })
    console.clear();
    console.log(res);
    const a = document.createElement("a"); 
    a.href = "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64," + res.fileContents; 
    a.download = res.fileDownloadName;
    a.click(); 
    a.remove();
},

reading the file does not present any problem
Greetings

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

笔落惊风雨 2025-02-05 22:45:01

假设您在FTP上的文件没有损坏,问题是.xlsx文件不是文本文件,而是streamReader旨在读取文本。随着您的使用,将损坏任意二进制数据(例如.xlsx文件)。

我个人只会通过您的服务器从FTP传输文件,然后直接传输到客户端:

public async Task<TransacResult> DownloadFileInterface(Uri serverUri, string fileName)
{
    StreamReader sr;
    byte[] fileContent;
    try
    {
        string ftpUser = GetConfiguration()["SuatKeys:FTPSuatUser"];
        string ftpPassword = GetConfiguration()["SuatKeys:FTPSuatPassword"];

        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
        request.Method = WebRequestMethods.Ftp.DownloadFile;
        request.KeepAlive = false;
        request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
        
        Stream ftpFileStream = request.GetResponse().GetResponseStream();
        var fileContentResult = new FileStreamResult(ftpFileStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        {
            FileDownloadName = fileName + ".xlsx"
        };
        return new TransacResult(true, fileContentResult);
    }
    catch (Exception ex)
    {
        return new TransacResult(false, new Message("SUAT-ERR-C02", MessageCategory.Error, "Conexión rechazada", ex.Message));
    }
}

Assuming you the file on FTP isn't corrupted, the problem have is that .xlsx files are not textual files, but StreamReader is intended for reading text. Using it as you are will corrupt arbitrary binary data (e.g. an .xlsx file).

I would personally just stream the file from FTP, through your server, and straight to the client:

public async Task<TransacResult> DownloadFileInterface(Uri serverUri, string fileName)
{
    StreamReader sr;
    byte[] fileContent;
    try
    {
        string ftpUser = GetConfiguration()["SuatKeys:FTPSuatUser"];
        string ftpPassword = GetConfiguration()["SuatKeys:FTPSuatPassword"];

        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
        request.Method = WebRequestMethods.Ftp.DownloadFile;
        request.KeepAlive = false;
        request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
        
        Stream ftpFileStream = request.GetResponse().GetResponseStream();
        var fileContentResult = new FileStreamResult(ftpFileStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        {
            FileDownloadName = fileName + ".xlsx"
        };
        return new TransacResult(true, fileContentResult);
    }
    catch (Exception ex)
    {
        return new TransacResult(false, new Message("SUAT-ERR-C02", MessageCategory.Error, "Conexión rechazada", ex.Message));
    }
}
沫离伤花 2025-02-05 22:45:01

我有这个确切的问题。事实证明,如果您使用某些中间件进行记录,它会迫使将流转换为与Excel不相容的文本表示形式。我唯一的工作是不使用中间件。

我在这个问题上发现了这一点: https://github.com/github.com/dotnet/dotnet/aspnetcore/issues/sissues/- 3304

I had this exact issue. Turns out, if you're using certain middleware for logging, it forces the stream to be converted to a text representation which is incompatible with Excel. The only work-around I have is to not use the middleware.

I found this out on this issue: https://github.com/dotnet/aspnetcore/issues/3304

ヅ她的身影、若隐若现 2025-02-05 22:45:01

我尝试了三次操作:

[HttpPost]
        public FileResult download(IFormFile file)
        {
            var filestream = file.OpenReadStream(); 
            var filestreamreader = new StreamReader(filestream, Encoding.Default);          
            var fileContent1 = Encoding.Default.GetBytes(filestreamreader.ReadToEnd());
            return File(fileContent1, "application/ms-excel", "3.xlsx");
            
        }

[HttpPost]
        public FileResult download1(IFormFile file)
        {
            var filestream = file.OpenReadStream();
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            ExcelPackage package = new ExcelPackage(filestream);
            var fileContent = package.GetAsByteArray();
            return File(fileContent, "application/ms-excel", "3.xlsx");
        }

首先,我尝试读取TXT文件和XLSX文件的内容,您可以看到我们可以获取TXT文件的内容字符串,但未能在XLSX文件中获取字符串,

然后我尝试尝试再次使用Epplus从流中获取内容字节并成功
结果:

我推荐Eeplus的原因:如果OneDay,我们想下载带有额外信息的XLSX文件,我们可以添加一些代码而不是删除代码,然后再次写入代码
代码如下;

[HttpPost]
        public FileResult download1(IFormFile file)
        {
            var employeelist = new List<Employee>()
            {
                new Employee(){Id=1,Name="Jhon",Gender="M",Salary=5000},
                new Employee(){Id=2,Name="Graham",Gender="M",Salary=10000},
                new Employee(){Id=3,Name="Jenny",Gender="F",Salary=5000}
            };
            
            var stream = file.OpenReadStream();
            
             
            byte[] fileContent;
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            using (ExcelPackage package = new ExcelPackage(stream))
            {
                // add a new worksheet to the empty workbook
                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Employee");
                
                //Set the Width and Height
                //worksheet.Column(1).Width = xx;
                //worksheet.Row(1).Height = xx;
                
                //Add the headers

                worksheet.Cells[1, 1].Value = "ID";
                worksheet.Cells[1, 2].Value = "Name";
                worksheet.Cells[1, 3].Value = "Gender";
                worksheet.Cells[1, 4].Value = "Salary (in $)";
                for(int i=0; i< employeelist.Count; i++)
                {
                    worksheet.Cells[i + 2, 1].Value = employeelist[i].Id;
                    worksheet.Cells[i + 2, 2].Value = employeelist[i].Name;
                    worksheet.Cells[i + 2, 3].Value = employeelist[i].Gender;
                    worksheet.Cells[i + 2, 4].Value = employeelist[i].Salary;
                } 
                package.Save(); //Save the workbook.
                fileContent = package.GetAsByteArray();
            }            
            return File(fileContent, "application/ms-excel", "target.xlsx");
        }

结果:

I tried three times with two Actions:

[HttpPost]
        public FileResult download(IFormFile file)
        {
            var filestream = file.OpenReadStream(); 
            var filestreamreader = new StreamReader(filestream, Encoding.Default);          
            var fileContent1 = Encoding.Default.GetBytes(filestreamreader.ReadToEnd());
            return File(fileContent1, "application/ms-excel", "3.xlsx");
            
        }

[HttpPost]
        public FileResult download1(IFormFile file)
        {
            var filestream = file.OpenReadStream();
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            ExcelPackage package = new ExcelPackage(filestream);
            var fileContent = package.GetAsByteArray();
            return File(fileContent, "application/ms-excel", "3.xlsx");
        }

At First,I tried to read the content of txt file and xlsx file ,you could see we could get the content string of txt file,but failed to get the string in xlsx file

Then I tried to get the content byte from stream again with EPPlus and succeeded
The ResulT:

The reason I recomanded EEplus: If Oneday we want to download the xlsx file with some extra infomation,we could just add some codes rather than delet the codes and write again
codes as below;

[HttpPost]
        public FileResult download1(IFormFile file)
        {
            var employeelist = new List<Employee>()
            {
                new Employee(){Id=1,Name="Jhon",Gender="M",Salary=5000},
                new Employee(){Id=2,Name="Graham",Gender="M",Salary=10000},
                new Employee(){Id=3,Name="Jenny",Gender="F",Salary=5000}
            };
            
            var stream = file.OpenReadStream();
            
             
            byte[] fileContent;
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            using (ExcelPackage package = new ExcelPackage(stream))
            {
                // add a new worksheet to the empty workbook
                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Employee");
                
                //Set the Width and Height
                //worksheet.Column(1).Width = xx;
                //worksheet.Row(1).Height = xx;
                
                //Add the headers

                worksheet.Cells[1, 1].Value = "ID";
                worksheet.Cells[1, 2].Value = "Name";
                worksheet.Cells[1, 3].Value = "Gender";
                worksheet.Cells[1, 4].Value = "Salary (in $)";
                for(int i=0; i< employeelist.Count; i++)
                {
                    worksheet.Cells[i + 2, 1].Value = employeelist[i].Id;
                    worksheet.Cells[i + 2, 2].Value = employeelist[i].Name;
                    worksheet.Cells[i + 2, 3].Value = employeelist[i].Gender;
                    worksheet.Cells[i + 2, 4].Value = employeelist[i].Salary;
                } 
                package.Save(); //Save the workbook.
                fileContent = package.GetAsByteArray();
            }            
            return File(fileContent, "application/ms-excel", "target.xlsx");
        }

The Result:
enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文