2

我最近使用 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);}
4

1 回答 1

1

要使用渐进式 Web 应用程序作为通用 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 中可用,即使它们没有为 JavaScript记录

查看FileSavePicker 类文档以获取更多信息。

于 2020-02-11T19:40:58.993 回答