我最近开发了一个带有UWP Web上下文(因此JavaScript和HTML)的Windows 10通用应用程序,我想保存一个文本文件。它适用于浏览器(Chrome,Firefox,Edge,...),但不适用于应用程序。 有人能帮我吗? :) 提前谢谢!
以下是负责保存文本文件的代码。
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);}
答案 0 :(得分:1)
要使用Progressive Web App作为通用Windows平台下载文件,可以将Windows
全局对象与FileSavePicker
一起使用。请注意,您可以使用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");
}
});
这假设您正在下载文本文件。要下载Uint8Array
,请使用WriteBytesAsync
上的FileIO
函数。请注意,FileIO
上的许多功能即使不是JavaScript的documented也可以在JavaScript中使用。
查看FileSavePicker Class documentation以获得更多信息。