2

I recently developed a universal application for Windows 10 with UWP web context (so JavaScript and HTML) and I would like to save a text file. It works well on a browser (Chrome, Firefox, Edge,...) but not in the application. Can someone help me? :) Thank you in advance!

Here is the code responsible for saving the text file.

function saveTextAsFile(fileName) {
var source = input.value.replace(/\n/g, "\r\n");
var fileUrl = window.URL.createObjectURL(new Blob([source], {type:"text/plain"}));
var downloadLink = createDownloadLink(fileUrl, fileName);

document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);}

1 Answers1

1

To download a file using a Progressive Web App as a Universal Windows Platform you can use the Windows global object with the FileSavePicker. Note that you can check to see if it exists using if (window['Windows'] != null) { ... }

// Create the picker object and set options
var savePicker = new Windows.Storage.Pickers.FileSavePicker();
savePicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.documentsLibrary;
// Dropdown of file types the user can save the file as
savePicker.fileTypeChoices.insert("Plain Text", [".txt"]);
// Default file name if the user does not type one in or select a file to replace
savePicker.suggestedFileName = "New Document";

savePicker.pickSaveFileAsync().then(function (file) {
    if (file) {
        // Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
        Windows.Storage.CachedFileManager.deferUpdates(file);
        // write to file
        Windows.Storage.FileIO.writeTextAsync(file, fileContents).done(function () {
            // Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
            // Completing updates may require Windows to ask for user input.
            Windows.Storage.CachedFileManager.completeUpdatesAsync(file).done(function (updateStatus) {
                if (updateStatus === Windows.Storage.Provider.FileUpdateStatus.complete) {
                    WinJS.log && WinJS.log("File " + file.name + " was saved.", "sample", "status");
                } else {
                    WinJS.log && WinJS.log("File " + file.name + " couldn't be saved.", "sample", "status");
                }
            });
        });
    } else {
        WinJS.log && WinJS.log("Operation cancelled.", "sample", "status");
    }
});

This assumes you are downloading a text file. To download a Uint8Array use the WriteBytesAsync function on FileIO instead. Note that many of the functions on FileIO are available in JavaScript even though they are not documented for JavaScript.

Check out the FileSavePicker Class documentation for more information.

Will M
  • 11
  • 1