Can files be saved using AngularJS JavaScript with Windows-1250 encoding?

I am currently working on a web application using AngularJS and SpringBoot API REST.
My challenge involves calling a REST API with a GET request to retrieve a flow of text data, and then attempting to save this data in a file with the charset WINDOWS-1250.

Scenario :
1) The AngularJS client initiates a GET request to the API REST
2) The API REST reads from a database, processes the data, and returns the result in the response body
3) The AngularJS client tries to save the result in a file with charset WINDOWS-1250.

However, when I attempt to save the file using FileSaver.saveAs, the file ends up being encoded in UTF-8 instead of Windows-1250, despite specifying the charset as Windows-1250.

Can anyone offer assistance with this issue?

Angular Test Script:

$http({method:'GET',   
       url: $scope.url + "/cmpcode/" + this.demand.company + "/pcmcode/" + this.demand.pcmcode + "/prlcode/" + this.demand.prlcode +  "/user/" + this.demand.user,  
       responseType : "blob" ,  
       headers:{'X-Auth-Token': sessionService.getLogonDatas.token}})  
.then(function(response) {  
    $scope.showErrorAlert = false;  
    var data = new Blob([response.data], { type: 'text/plain; charset=Windows-1250' });  
    FileSaver.saveAs(data, "MyFile.test");  
    $scope.showSuccessAlert = true;},  
function(rejection) {  
    $scope.showSuccessAlert = false;  
    if (rejection.status === 406){$scope.message.code = "NO_ROWS";}  
    $scope.showErrorAlert = true;});   
};  

SpringBoot Test APIREST:

public void getPaymentNationalFile(HttpServletResponse response,
                                       @PathVariable("cmpcode") @Length(max = 12) @NotNull String companyCode,
                                       @PathVariable("pcmcode") @Length(max = 12) @NotNull String pcmcode,
                                       @PathVariable("prlcode") @Length(max = 12) @NotNull String prlcode,
                                       @PathVariable("user") @Length(max = 12) @NotNull String user,
{
//Without Try & Catch
PaymentNationalParam paymentNationalParam = new PaymentNationalParam(companyCode, pcmcode, prlcode, user);  
paymentNationalData = paymentNationalService.GetFilePaymentNational(paymentNationalParam);  
response.setContentType("text/plain;charset=" + paymentNationalData.getCharacterEncoding());  //Here "Windows-1250"
int longueur = 0 ;
byte[] buffer = null;
ServletOutputStream servletOutputStream = response.getOutputStream();
for (String string : paymentNationalData.prepareLignePaymentToWrite()) 
{
    buffer = (string + "\n").getBytes() ;
    longueur += buffer.length;
    servletOutputStream.write(buffer , 0, buffer.length);
}
response.setContentLength(longueur);
servletOutputStream.flush();
}

API Response (extract)

Header :
Content-Type : text/plain;charset=windows-1250
Transfer-Encoding : chunked
X-Content-Type-Options : nosniff

Body extract -> line 1 and 2 of the response (more lines): 110,20170626,2594917,10500086,0,"29105000861000002274422993","16105010701000000101025518","NORAUTO POLSKA SP Z.O.O|UL. JUBILERSKA 10||04190 WARSZAWA","AUTOLAND
43-25|MICKIEWICZA 28| 0|43-250 PAWĹOWICE",0,10501070,"114024","","","51",""

110,20170626,70725,10500086,0,"29105000861000002274422993","58103015080000000502563009","NORAUTO POLSKA SP Z.O.O|UL. JUBILERSKA 10||04190 WARSZAWA","BOSCH ROBERT SP02-23|JUTRZENKI 105| 0|02-231 WARSZAWA",0,10301508,"114025","","","51",""

Answer №1

I managed to find a solution, although I am uncertain of its quality.

In the Java section, my approach involves setting the response as an octet-stream and including this in the Content-type header.

response.setContentType("application/octet-stream;charset=" + paymentNationalData.getCharacterEncoding());

As for the AngularJS part, the file is saved with the appropriate Content-type Header.

var data = new Blob([response.data],{type: response.headers('Content-Type')}); 
FileSaver.saveAs(data, response.headers('content-filename'));

And it works like a charm!

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

Migration unsuccessful due to incompatible peer dependencies detected - Updating Angular to Version 12 was not successful

Currently in the process of upgrading my Angular v11 apps to Angular v12. Encountering an error while attempting to upgrade Angular packages: ng update @angular/core@12 @angular/cli@12 Error: Migration failed due to incompatible peer dependencies The pa ...

Guide to building a React project with an outdated edition of Create React App

Currently, I'm following an older tutorial to learn React, and as a result, I need to set up a project using Create React App version 1.5.2. I successfully installed <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="204352454 ...

Experiencing problems with CSS compatibility while transitioning from vanilla JavaScript to React

Currently, I am working on revamping the frontend of an app that was initially built with vanilla javascript and transitioning it to a React framework. However, I'm encountering some challenges with styling the HTML elements. Specifically, the textare ...

Creating a Dynamic Counter for Real-Time Message Updates in a Personal Messaging Application with jQuery

I am currently in the process of developing a Personal Message System for my website. My goal is to have the number of new messages in each chat displayed and updated in real-time, just like the red "box" showcased in the screenshot below: https://i.sstati ...

Utilize JavaScript and CSS to create dynamic text animations

(() => { const paraElement = document.querySelector('#animated-text'); const spanElement = paraElement.querySelector('span'); const wordsList = JSON.parse(spanElement.dataset.words); let counter = 0; setInterval(funct ...

Troubleshooting issues with extending Material UI theme using Module Augmentation

I want to customize the background field in the palette by adding an "input" property and updating the Theme to include different types, like this: export const lightTheme = createTheme(commonTheme, { palette: { mode: 'light', backgroun ...

What is preventing the table from extending to the full 100% width?

Displayed above is an image showing an accordion on the left side and content within a table on the right side. I have a concern regarding the width of the content part (right side) as to why the table is not occupying 100% width while the heading at the ...

The Angular service "this" is altering the context of the window object

I must have made a mistake somewhere and I know I am overlooking something obvious. The aim is to create a service that provides basic authentication features such as login, logout, and checking if a user is logged in or not. Upon loading the page, I veri ...

What is the most efficient way to access a cell within an HTML table using jQuery or the Document Object Model (

I have an unchangeable HTML table styled with CSS. My goal is to extract the value from the first column for filtering purposes. I've been struggling to locate a suitable jQuery or DOM function to accomplish this task. Unable to find a way to access ...

Expanding Vue JS Vuetify Panels in a V-for Loop to Reveal Multiple Panels

When pulling data from a database and looping through it in the DOM using a "v-for" loop, I encountered an issue with Vuetify expansion panel components. The problem is that when a user clicks to open one expansion panel, it ends up opening all other panel ...

Error in zone: 140 - Property 'remove' is not readable

I'm brand new to kendo ui. I successfully set up a prototype in my fiddle with a working delete confirmation window. However, when I try to integrate it into my existing codebase, I encounter an error: Cannot read property 'remove' at the li ...

Transform an { Key : Value } Object into Regular Variables using jQuery

Here is a code snippet in PHP: foreach($myarray as $key=>$value) { ${$key} = $value; } Now, I am wondering if we can achieve the same functionality using JS/jQuery? In this jQuery example, I am trying to assign the value of each td element with a cla ...

Elevate sublevel vue component

I am facing an issue with a nested and reused vue component. I am attempting to use v-show to display a part of the component (icons) when its outer parent is hovered. In order to achieve this, I am passing the parent and child index as props. However, I ...

What is the best approach for managing caching effectively?

My SPA application is built using Websocket, Polymer, ES6, and HTML5. It is hosted on a Jetty 9 backend bundled as a runnable JAR with all resources inside. I want to implement a feature where upon deploying a new version of the JAR, I can send a message ...

CSS Attribute Selector Wildcard Capture Tool

Suppose I have the following HTML structure: <div class="tocolor-red"> tocolor </div> <div class="tocolor-blue"> tocolor </div> <div class="tocolor-green"> tocolor </div> <div class="tocolor-yellow"> tocolor ...

Vue router beforeRouteEnter - when the page is refreshed, the button label vanishes

<script> export default { name: 'TEST', data() { return { prevRoute: '' } }, methods: { goBack() { return this.$router.go(-1); }, }, beforeRouteEnter(to, from, next) { next(vm => { ...

Using the information retrieved from Google Place Autocomplete and saving it for future reference

I am interested in utilizing the Google API "Place Autocomplete" widget to enhance user experience on my website. The specific widget I have in mind can be found here. My goal is to streamline the process of obtaining property addresses from Real Estate A ...

Unable to render any charts with angular-chart.js

Utilizing the dependency angular-chart.js in my angular project has allowed me to showcase data visualizations on my admin page. Recently, I decided to upgrade angular-chart.js to version 1.1 and Chart.hs to version 2.5 based on the README.md guidelines o ...

Retrieve the error message sent to the next() method in mongoose middleware and pass it to the client controller

While I am new to MEAN stack and still learning, I have encountered a question that I hope someone can help me with. I am struggling to pass a custom error message from my Mongoose pre-save hook middleware to my AngularJS controller. In my code, I am u ...

What is the way to display the final list item when clicking in jQuery?

I am attempting to achieve a specific behavior where clicking on a button will trigger the content below to scroll in such a way that only the last item in the list is visible. I have been using jQuery for this functionality, but unfortunately, it is not ...