Javascript 在UWP web上下文中保存文件
我最近开发了一个带有UWP web上下文(JavaScript和HTML)的Windows 10通用应用程序,我想保存一个文本文件。它在浏览器(Chrome、Firefox、Edge等)上运行良好,但在应用程序中不起作用。 有人能帮我吗?:) 提前谢谢你 下面是负责保存文本文件的代码Javascript 在UWP web上下文中保存文件,javascript,uwp,webcontext,Javascript,Uwp,Webcontext,我最近开发了一个带有UWP web上下文(JavaScript和HTML)的Windows 10通用应用程序,我想保存一个文本文件。它在浏览器(Chrome、Firefox、Edge等)上运行良好,但在应用程序中不起作用。 有人能帮我吗?:) 提前谢谢你 下面是负责保存文本文件的代码 function saveTextAsFile(fileName) { var source = input.value.replace(/\n/g, "\r\n"); var fileUrl = window.U
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);}
要使用渐进式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
请改用FileIO
上的WriteBytesAsync
功能。请注意,FileIO
上的许多函数在JavaScript中可用,即使它们不适用于JavaScript
查看以获取更多信息。查看以及如何在那里保存文件。我不能使用C方法,这不是C方法-它是WinRT方法。您可以从JavaScript调用WinRT API。例如,见