The issue of incorrect encoding in JavaScript Blob while retrieving a file from the server

Implementing a FileStreamResult from C# in a SPA website (using .NET Core 2, SPA React template), I make a request to fetch a file from my endpoint. This triggers the following response in C#:

var file = await _docService.GetFileAsync(token.UserName, instCode.Trim()
.ToUpper(), fileSeqNo);
string contentType = MimeUtility.GetMimeMapping(file.FileName);
var result = new FileStreamResult(file.File, contentType);
var contentDisposition = new ContentDispositionHeaderValue("attachment");
Response.Headers[HeaderNames.ContentDisposition] = 
contentDisposition.ToString();
return result;

The response received is then processed using msSaveBlob (specifically for MS, although issues arise even when using createObjectURL and a different browser. Despite trying various solutions, none seem to work). Below is the code snippet used to send the request and receive the PDF FileStreamResult from the server.

if (window.navigator.msSaveBlob) {
  axios.get(url).then(response => {
      window.navigator.msSaveOrOpenBlob(
          new Blob([response.data], {type: "application/pdf"}),
          filename);
  });

The issue arises when the PDF file received has incorrect encoding, causing it not to open properly.

Attempts to rectify this include adding encoding to the end of type:

{type: "application/pdf; encoding=UTF-8"}
as suggested in various forums, but without success.

By comparing the PDF file fetched using a different method, it is evident that the encoding is incorrect. Special characters are not displayed correctly, despite the response header indicating that the PDF file should be in UTF-8. Unfortunately, I am unsure how to verify and rectify this.

Answer №1

Upon initial review of axios, it appears that by default it utilizes JSON as the responseType based on information provided on its readme page. This could potentially lead to content alteration, treating the response as text if it cannot be converted to a JSON object, thus maintaining the original string/text source for the response data.

According to the Adobe PDF reference sec. 2.2.1, a PDF file should be loaded as binary data, regardless of whether it contains 8-bit binary content or 7-bit ASCII. Both scenarios should be handled as byte streams, as PDF files are intended to be cross-platform and represented by sequences of 8-bit binary bytes.

PDF files are represented as sequences of 8-bit binary bytes. A PDF file is designed to be portable across all platforms and operating systems. The binary representation is intended to be generated, transported, and consumed directly, without translation between native character sets, end-of-line representations, or other conventions used on various platforms. [...].

Any PDF file can also be represented in a form that uses only 7-bit ASCII character codes. This is useful for the purpose of exposition, as in this book. However, this representation is not recommended for actual use, since it is less efficient than the normal binary representation. Regardless of which representation is used, PDF files must be transported and stored as binary files, not as text files. [...]

To address the conversion issue, it is recommended to specify the responseType in the request configuration:

axios.get(url, {responseType: "arraybuffer"}) ...

Alternatively, you can use the following format:

axios({
  method: 'get',
  url: url,
  responseType:'arraybuffer'
})
.then( ... )

If you are confident that the mime-type is maintained during the process, you may opt for the blob response type directly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue.js <v-data-table> - Automatic sorting/ custom sorting options

I am trying to arrange the numerical data in a Vue.js data-table in descending order right from the start. I want it to look like the screenshot provided below. Screenshot of My Desired Result The data that needs to be arranged in descending order is the ...

Modify the href value by matching it with the parent div attribute

I am working on an HTML project <div class="1" style="" title="NeedthisText TextIDontneed"> <div class="2> <div class="3"> <a target="_blank" href="/NeedToChange/DispForm.aspx?ID=1"></a> </div> </div> &l ...

Utilizing data as a substitute when creating a SearchBar using Vue3

My VueJs3 application has a search bar implemented using .filter(), and it seems to be working fine. However, when I try to pass the value from my methods to the template, an error occurs. My data becomes a proxy and I am unable to use it in that format. ...

How can I use jQuery to set up form validation for an input textfield?

Check out this code snippet: <form data-test="loginForm-container" novalidate="" method="POST" enctype="multipart/form-data"> <div class="css-o5d3v1 e1ovefus2"> <div data-test="guestForm-email-wrapper" class="e1ovefus1 css-yjv4po e1eu3s ...

Javascript postback functionality is fully operational in bootstrap 4, however, it is failing to return

Encountering an issue with my postback JavaScript function in the ASP/BootStrap environment. After searching on stackoverflow for a solution, I couldn't find one that resolved my problem. The problem is when I click on an image, the page reloads (the ...

What steps should be taken to address the Chrome alert stating that the deferred DOM Node cannot be identified as a valid node?

While working on my node.js project hosted on a localhost server, I've encountered an unusual warning message in the inspector. The warning states: The deferred DOM Node could not be resolved to a valid node. Typically, I use the inspector to examine ...

Having trouble updating an array in a mongoose document?

Need help with updating an array in a document by adding or replacing objects based on certain conditions? It seems like only the $set parameter is working for you. Here's a look at my mongoose schema: var cartSchema = mongoose.Schema({ mail: Stri ...

Reposition the span element to the right of the div tag

I need help adjusting the positioning of the elements in this HTML code. How can I move the span element with the image to the right of the div tag? Here is the code snippet: <div style='width:600px;padding-top: 2px;padding-bottom: 1px'& ...

Issue: In an Angular electron app, a ReferenceError is thrown indicating that 'cv' is

I have been working on a face detection app using OpenCv.js within an Angular electron application. To implement this, I decided to utilize the ng-open-cv module from npm modules. However, when attempting to inject the NgOpenCVService into the constructor ...

Is there a way to remove the "next" button from the last page in a table?

I'm currently working on implementing pagination for my table. So far, I have successfully added both the "next" and "previous" buttons, with the "previous" button only appearing after the first page - which is correct. However, I am facing an issue w ...

"AngularJS View Source Page: Unveiling the Power of Dynamic Metatags

Hey there, I have a requirement where I need to update the metatags content dynamically. I successfully updated the content in INSPECT ELEMENT, but I am unable to see the updated content in the view source page. I want to update the metatags in the view ...

Discovering which particular check in the Express Validator is causing the errors can be done by following these steps

I am currently developing a web application that requires an admin user to create new users. The admin user's username and password are stored in the .env file, and I am utilizing the dotenv package for this purpose. However, I am facing an issue when ...

utilizing axios encoding settings within vue.js

I am currently utilizing vue.js along with axios to retrieve data from an API endpoint. The specific URL I require is structured like this: https://base_url.com?f=json&where=&returnGeometry=false&spatialRel=esriSpatialRelIntersects&geometr ...

Highlight a pair of words in a phrase using jquery technology

Only one word in my code is highlighted $(document).ready(function() { let firstword = 'web'; let secondword = 'js'; $(".field.ConditionsAccept>.caption:contains('" + secondword + "'):contains('" + firstword ...

Creating a simulated loading screen

I have created a preloader page for my website following tutorials, such as the one found here: https://codepen.io/bommell/pen/OPaMmj. However, I am facing a challenge in making this preloader appear fake without using heavy content like images or videos. ...

The hovering event trail feature is not functioning in tsParticles, unlike in particlejs

I have two questions regarding the implementation of tsParticles in my React application. First question: <Particles id="tsparticles" options={{ background: { color: { value: "black&quo ...

Creating JSON with PHP: Ensuring consistent keys in JSON output derived from PHP arrays

Is there a method to convert a PHP array (or any other similar PHP object) into JSON while maintaining identical keys for a JSON array? For example: {"categories" : [ {"key": "data1"}, {"key": "data2"}, {"key": "data3" } ] } It is worth noting that the ...

In the realm of JavaScript, removing a DOM element can sometimes feel like an

For my project, I am using JavaScript, DOM, and AJAX to create pages. I am trying to figure out how to check if an element already exists and, if it does, remove it. This is what I have tried: var elementL = document.getElementById('divLogin'); ...

I can't seem to figure out what's causing this error to pop up in my coding setup (Tailwind + Next.js). It

I've been struggling with this problem for a week now and despite my efforts, I haven't been able to find a solution yet. However, I have made some progress in narrowing down the issue. The problem arises when I try to execute the yarn build comm ...

retrieving data from a node and embedding it into an HTML file

In my project, I have an index.html file and an app.js nodejs file. Within the app.js file, there is a variable named "name" that I would like to display in my index.html page. Here is the code snippet: var name = "Utsav"; var HTTP = require('HTTP&a ...