Skip to content

Instantly share code, notes, and snippets.

@mjfusa
Created October 25, 2019 22:56
Show Gist options
  • Save mjfusa/864140648f5720fa2e471439741de112 to your computer and use it in GitHub Desktop.
Save mjfusa/864140648f5720fa2e471439741de112 to your computer and use it in GitHub Desktop.
File Save from (Spartan) Edge PWA
<script>
function saveBlob (blob, fileName) {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
async function SaveAs(blob, fileName) {
// Test if we're running ing the Spartan (Edge) UWP / PWA Context
if (window.Windows) {
var text = await (new Response(blob)).text();
// Create the picker object and set options
var savePicker = new Windows.Storage.Pickers.FileSavePicker();
savePicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.downloads;
// 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 = fileName;
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, text).then(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.
return Windows.Storage.CachedFileManager.completeUpdatesAsync(file);
}).done(function (updateStatus) {
if (updateStatus === Windows.Storage.Provider.FileUpdateStatus.complete) {
console.log("File " + file.name + " was saved.", "sample", "status");
} else {
console.log("File " + file.name + " couldn't be saved.", "sample", "status");
}
});
} else {
console.log("Operation cancelled.", "sample", "status");
}
});
} else {
saveBlob(blob, fileName);
}
}
function dl() {
var blobObject = new Blob(["I'm completely operational, and all my circuits are functioning perfectly."]);
SaveAs(blobObject, 'test.txt');
}
</script>
<button type="button" onclick="dl()">Click</button>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment