Home > Software design >  "Word found unreadable content" after downloading file with C# Web API
"Word found unreadable content" after downloading file with C# Web API

Time:12-23

What I'm Trying To Do

I have an Angular client app that needs to download a file (in my case an editable Word Document). This file is on a network drive.

What I'm Getting

I've been trying different solutions and from all of them I've had different results. But mostly there was a JSON or a Word file with unreadable content. Or even an error. I have no idea how to fix it, I checked almost every solution I was able to find.

Things I've Tried

These are some of the solutions I utilized:

My code

C# Web Api

[ApiController]
[EnableCors("AllowOrigin")]
[Route("api/ct-test")]
public class CtTestController : ControllerBase
{
    private ReportService _reportService;

    public CtTestController(ReportService reportService)
    {

        _reportService = reportService;
    }

    [HttpGet]
    [Route("report")]
    public async Task<IActionResult> GetReport()
    {
        try
        {
            string directory = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Files/");

            if (!Directory.Exists(directory)) Directory.CreateDirectory(directory);

            var path = Path.Combine(directory, "report.docx");

            byte[] data = null;

            string contentType = "";

            var provider = new FileExtensionContentTypeProvider();

            if (System.IO.File.Exists(path))
            {
                data = System.IO.File.ReadAllBytes(path);

                if (!provider.TryGetContentType(path, out contentType))
                {
                    contentType = "application/octet-stream";
                }
            }

            return Ok(File(data, contentType, "report.docx"));
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }
}

Angular Service

getReport(): Observable<Blob> {
  this.url = "http://localhost:4202/api/ct-test/report";
  return this.http.get(this.url, { responseType: 'blob'});
}

Angular Component

getReport() {
  this.reportService.getReport().subscribe({
    next: (response: Blob) => {
      {
        saveAs(response, 'report.docx');
      }
    },
    error: (error: any) => {
      console.error('There was an error!', error);
    },
  })
}

What am I doing wrong? Maybe I missed something obvious. Any help is appreciated. Many thanks in advance.

CodePudding user response:

From your code one error is in:

return Ok(File(data, contentType, "report.docx"));

It should be just:

return File(data, contentType, "report.docx");

The File method returns a FileContentResult with a 200 status code (if everything is how it should be). You shouldn't wrap it in the Ok method.

  • Related