Home > Mobile >  FileContentResult return excel file corrupt
FileContentResult return excel file corrupt

Time:05-19

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

CodePudding user response:

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

CodePudding user response:

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:

  • Related