Search code examples
javascriptwindows-store-appswin-universal-appwinjswindows-10-universal

How Can You Save Multiple Files At Once with WinJS?


I'm making a WinJS app for Windows Store for Windows 8 and 10. I'm producing an app for my company, and at the end of a user process they are expected to click an Export button which saves about 10 files to a folder of their choosing.

Now, I know how to use a Windows.Storage.Pickers.FileSavePicker() to save individual files, but I don't want to give the user the burden of accepting the save of each of the 10 files -- I just want the user to accept the folder they're going into, and then it saves them all in one swoop.

Is that possible in WinJS?


Solution

  • but I don't want to give the user the burden of accepting the save of each of the 10 files -- I just want the user to accept the folder they're going into, and then it saves them all in one swoop.

    You can use FolderPicker to get the target folder and use StorageFolder.CreateFileAsync to generate 10 files and copy the contents you want to the file:

    var pickers = Windows.Storage.Pickers;
    var DataWriter = Windows.Storage.Streams.DataWriter;
    ...
    document.getElementById("btnSave").onclick = function (evt)
    {
           var content = "Test Content";
           var picker = new pickers.FolderPicker();
           picker.suggestedStartLocation = pickers.PickerLocationId.computerFolder;
           picker.fileTypeFilter.append(".txt");
           picker.pickSingleFolderAsync().then(function (folder) {
           if (folder != null)
           {
               for (var i = 1; i < 11; i++) {
                   folder.createFileAsync("testFile" +i+ ".txt", Windows.Storage.CreationCollisionOption.replaceExisting)
                        .then(function (file) {
                            file.openAsync(Windows.Storage.FileAccessMode.readWrite)
                                .then(function (randomAccessStream) {
                                    var dataWriter = new DataWriter(randomAccessStream.getOutputStreamAt(0));
                                    dataWriter.writeString(content);
                                            dataWriter.storeAsync().done(function () {
                                                randomAccessStream.close();
                                                dataWriter.close();
                                    });
                                }, errorHandler);
                        }, errorHandler);
                    }
                }
            }, errorHandler)
    }
    
    function errorHandler(error){}