How can I save a blob to a text file?

When trying to save the text written to a file in a new window locally, I encountered an error while using the saveAs and msSaveBlob methods.

window.navigator.msSaveBlob(blob, 'msSaveBlob_testFile.txt');

var blob = new Blob([output], {type: "text/plain;charset=utf-8"}); saveAs(blob, "thing.txt");

function exportGeometry ( ) {
    var output=[];
    output.push("//TLR:Format:Vishama Creations:v1.0\n//Pattern_no,Pattern_NumLines,FrstPointIndx,PointName,aX,aY,aZ,bX,bY,bZ,SecondPointIndex,PointName,aX,aY,aZ,bX,bY,bZ\nL\n");
    output.push(fpatternIndex);
    output.push(fpatternLineCount);
    output.push(fpatternPointCount);
    for(var b=0;b<fpatternLineCount;b++)
    {
        output.push(ffirstPtIndx[b]);
        output.push(fpatternPointName[ffirstPtIndx[b]]);
        output.push(fpatternPoint[ffirstPtIndx[b]].x/300);
        output.push(fpatternPoint[ffirstPtIndx[b]].y/300);
        output.push(fpatternPoint[ffirstPtIndx[b]].z/300);

        output.push(fsecondPtIndx[b]);
        output.push(fpatternPointName[fsecondPtIndx[b]]);
        output.push(fpatternPoint[fsecondPtIndx[b]].x/300);
        output.push(fpatternPoint[fsecondPtIndx[b]].y/300);
        output.push(fpatternPoint[fsecondPtIndx[b]].z/300);
    }
    output.push("\nL\n");
            output.push(bpatternIndex);
            output.push(bpatternLineCount);
            output.push(bpatternPointCount);
            for(var b=0;b<bpatternLineCount;b++)
            {
                output.push(bfirstPtIndx[b]);
                output.push(bpatternPointName[bfirstPtIndx[b]]);
                output.push(bpatternPoint[bfirstPtIndx[b]].x/300);
                output.push(bpatternPoint[bfirstPtIndx[b]].y/300);
                output.push(bpatternPoint[bfirstPtIndx[b]].z/300);

                output.push(bsecondPtIndx[b]);
                output.push(bpatternPointName[bsecondPtIndx[b]]);
                output.push(bpatternPoint[bsecondPtIndx[b]].x/300);
                output.push(bpatternPoint[bsecondPtIndx[b]].y/300);
                output.push(bpatternPoint[bsecondPtIndx[b]].z/300);
    }


    var blob = new Blob([output], {type: "text/plain;charset=utf-8"});

    var objectURL = URL.createObjectURL(blob);
    window.open(objectURL, '_blank');
    window.focus();

};

Attempting to use saveAs(blob ,test.txt) resulted in an error stating that saveAs is not defined.

Answer №1

Regrettably, none of the current browsers support the saveAs() function.

You can easily verify this using the following code snippet:

if (window.saveAs) {
    console.log("saveAs supported");
}else{
    console.log("saveAs not supported");
}

Returning to your issue, you have successfully generated a text file that is visible in a new window. To initiate the download in the browser, simply create an anchor element (<a></a>) and simulate a user click.

To achieve this, replace the

window.open( objectURL, '_blank' ); window.focus();
with the following lines of code:

Additional Code

var a = document.createElement('a');
a.download = "test.txt";
a.href = url;
a.click();// in case of failure, try using a.onclick();

Find a working example on

JSFiddle

Answer №2

I had a difficult time with this issue, but I found a solution that worked for me. I decided to ensure that my HTML only used supported browser versions. Internet Explorer was causing some unnecessary trouble by defaulting to lower versions, so I included the following code in the header of my HTML page:

<meta http-equiv="X-UA-Compatible" content="IE=10" />

Additionally, I made sure to declare my output variable outside of my function, yet still within the script tags. Here is an example:

<script src="FileSaver.js"></script>
<script>

var output; 

function exportGeometry( ) {

    var output=''; ...

If you are not already using FileSaver.js, you can find more information about it at: https://github.com/eligrey/FileSaver.js/

I hope this advice proves helpful to you, and I wish you the best of luck!

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

A single feature designed to handle various elements

I currently have this HTML code repeated multiple times on my webpage: <form class="new_comment"> <input accept="image/png,image/gif,image/jpeg" id="file" class="file_comment" key=comment_id type="file" name="comment[media]"> <spa ...

From HTML to Python to Serial with WebIOPi

I am facing a dilemma and seeking help. Thank you in advance for any guidance! My project involves mounting a raspberry pi 2 b+ on an RC Crawler rover, utilizing WebIOPi for the task. However, I am encountering challenges and unable to find useful resourc ...

Performing an XMLHttpRequest in the same JSP file using Javascript

I am working on a JSP file that contains three dropdown boxes labeled "countries", "regions", and "cities". My goal is to populate the regions based on the selected country, and the cities based on the selected region. I have managed to achieve this using ...

Using local variables from an external HTML file within an AngularJS directive template

Just making sure I am wording my question correctly, but I have not been able to find any information on this specific topic. Imagine I have an AngularJS directive that looks something like this: angular.module( 'example', [] ).directive( ...

What is the established procedure for resetting all elements within an (X)HTML document?

Is there a way to reset elements without using a form like how it can be done with JavaScript? document.forms[0].reset(); I am utilizing AJAX, so do I need to loop through all the elements using JavaScript? ...

What is the best way to fill a "multiselect" element with information from a JSON object?

I'm struggling to populate the multiselect field with data from a JSON object. No matter which multiselect I use, the data shows in inspect mode but not on the frontend. It was supposed to look like this. https://i.sstatic.net/FVz2H.png but it comes ...

What is the correct way to show a PHP script as an HTML page following an AJAX call?

Attempting to utilize AJAX to call a php file that will display an html page from my js. Below is the php file in question: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv=& ...

Setting the height attribute of an image tag in HTML to match a JavaScript variable

I am currently developing a SharePoint app that heavily relies on JavaScript. I have implemented a feature where the user can set a variable of their choosing, which I want to utilize as the width of an image displayed on the screen. This designated value ...

Changing scope is ineffective unless $scope.$apply is used

When a button is clicked, I have a directive that displays a loading screen. angular.module('randomButton', ['Data']) .directive('randomButton', function(Data) { return { scope: '=', restrict: ...

What is the best way to retrieve ember model relation properties within routes and controllers?

Currently using ember 2.7.0, I am facing an issue while setting up my ember app with a currentUser.organization derived from the authenticated token. Although I can successfully resolve the currentUser, I am encountering difficulties in resolving the prope ...

How does the object scope receive, process, and prepare the update for display within the AngularJs view?

AngularJS allows for data-binding to easily display immediate data in our View. This is made possible by the object scope, which acts as a connector between the Logic Code and The View. Additionally, AngularJs supports two-way binding. My question is: H ...

What is the functionality of the toArray method?

var retrieveDocs = function (db, callback) { var collection = db.collection('tours'); collection.find({ "tourPackage": "Snowboard Cali" }).toArray(function (err, data) { console.log(data); callback; }) } Is there a p ...

Executing a JQuery function from varying environments

While this question may seem basic, I am having trouble understanding the behavior described. I have written some JavaScript code and I am puzzled why the second call to foo does not work. You can find the code in this JSFiddle link. $.fn.foo = function( ...

Issues encountered when integrating a shader

I've created a shader and I'm trying to test it on Codepen. Despite having no errors in the console, the shader still isn't working as expected. Can anyone help me figure out what's going wrong? Below is my vertex shader: <script i ...

Implementing Autocomplete feature in Reactjs with Ant Design Library

In my React application, I created an autocomplete feature with a list of options for the user to select from. Example in Action: Click here to see the demo List of available options: const options = [ { label: "hello", value: "1" ...

Update in Angular version 1.5.9 regarding $location.hashPrefix causing changes

Previously, the default $location.hashPrefix was an empty string until version 1.5.8 of AngularJS, but it was changed to "!" in version 1.5.9. This modification has caused issues in my codebase where there are instances like <a ng-ref="/Customer#/{{cu ...

The relationship between two distinct servers: Express.js and Node.js

Working with the Express.js framework and Node.js, I am trying to make a request to an MS SQL database on the server side. My goal is to retrieve data (in JSON or array format) from the server and send it to the client side. I'm unsure about how to ...

Display or conceal several elements using JQUERY/HTML upon hovering

Here is the current progress: <div style="position: relative;"> <a href="#games"> <div class="sidenavOff"> <img src = "images/card_normal.png" /> <img src = "images/category_icons/icon_games.png" style = "position: a ...

Achieve SEO excellence with Angular 4 in production settings

I am currently building a website using Angular 4 as part of my personal study project. Although my website is live, I realized that it's not SEO friendly. After making some changes, I came across a valuable resource on server-side rendering in Angul ...

How can I dynamically insert a new HTML element into $event.target using Angular 2?

I have a webpage with a list of items. I want to display a "copy" button next to each item when the mouse hovers over it. I am currently able to create the "copy" button within the element using the following method: mouseOver(event) { if (event.tar ...