Quickstart: Send a file to a storage device (HTML)

Applies to Windows only

This tutorial shows you how to copy a file to a removable storage device by instantiating a storage object using Windows.Devices.Portable.Storage.FromId.

Objective: You'll learn how to use the Windows.Devices.Enumeration API to enumerate removable storage devices and choose one to use for instantiating a storage object, that can then be used as the target of a copyAsync operation.

Prerequisites

You should be familiar with JavaScript and HTML.

You need to have a removable storage device available.

Time to complete: 20 minutes.

Instructions

1. Open Microsoft Visual Studio

Open an instance of Microsoft Visual Studio.

2. Create a New Project

In the New Project dialog box, choose a blank application from the JavaScript project types.

3. Declare the Removable Storage Capability

Double click on package.appxmanifest in solution explorer. Select the Capabilities tab. Check Removable Storage in the Capabilities list.

4. Insert the Application JavaScript and HTML

Open your Default.html and copy the following HTML into it, replacing its original contents.



  
<!DOCTYPE html>
<html>
<head>
<title>Removable Storage Devices</title>
<link rel="stylesheet" href="/winjs/css/ui-dark.css" />
<script type = "text/javascript" >

    Enum = Windows.Devices.Enumeration;

    // Enumerate removable storage devices.
    // The success callback selects the removable storage to use.
    function pickStorage(){
        Enum.DeviceInformation.findAllAsync(
            Windows.Devices.Portable.StorageDevice.getDeviceSelector(),
            null).then(
                successCallback, 
                errorCallback);
    }

    // Handler that's called when removable storages are found.
    // The storageDevices parameter is of type
    // Windows.Devices.Enumeration.DeviceInformationCollection
    function successCallback(storageDevices){
        var removableStorage;
        if (storageDevices.length) {
            try {
                // Create an IStorageItem from the first removable storage device
                removableStorage = Windows.Devices.Portable.StorageDevice.fromId(
                    storageDevices.getAt(0).id);  
            } catch (e) {
                document.getElementById("output").innerHTML =
                    "Error creating storage item: " + e.message;
            }
            if (removableStorage != null) {
                PickAndSend(removableStorage, removableStorage.name);
            }
        }
    }                                

    function errorCallback(e) {
        document.getElementById("output").innerHTML = "Error: " + e.message;
    }

    // Pick a file, and send it to the removable storage device
    // removableStorage: The IStorageItem representing the storage device
    // removableStorageName: The name of the storage device
    function PickAndSend(removableStorage, removableStorageName) {
        // Create the picker for selecting an image file
        var picker = new Windows.Storage.Pickers.FileOpenPicker();
        // Set the collection of types that the file open picker displays.
        picker.fileTypeFilter.replaceAll([".jpg", ".png", ".gif"]);
        // Set the initial location where the file picker looks
        picker.suggestedStartLocation =
            Windows.Storage.Pickers.PickerLocationId.picturesLibrary;
        picker.pickSingleFileAsync().then(
        function (sourceFile) {
            // sourceFile is null if the user
        // clicked cancel from the picker
            if (sourceFile == null) {
                document.getElementById("output").innerHTML =
                "No file was picked.";
            }
            else {
                // Copy the file to the storage device
                // using StorageFile.copyAsync
                sourceFile.copyAsync(removableStorage).then(
                    function (newFile) {
                        document.getElementById("output").innerHTML =
                        "Created file: " + newFile.name + " on " +
                        removableStorageName + "<br/>";
                },
                    function (e) {
                    // A failure here could mean that the removable storage
                    // does not allow file creation on its root.
                    // We try to find a folder to copy the file to.
                    copyToFirstAvailableFolder(
                            removableStorage, sourceFile);
                });   // end sourceFile.copyAsync
            }             // end if (sourceFile)
        });               // end pickSingleFileAsync.then
    }

function copyToFirstAvailableFolder(removableStorage, sourceFile) {
    // Construct a recursive folder search
    var queryOptions = new Windows.Storage.Search.QueryOptions(
            Windows.Storage.Search.CommonFolderQuery.defaultQuery);
    queryOptions.folderDepth = Windows.Storage.Search.FolderDepth.deep;
    var deepFolderQuery =
            removableStorage.createFolderQueryWithOptions(queryOptions);

    deepFolderQuery.getFoldersAsync().then(
        function (folders) {
            copyToFolder(folders, 0, sourceFile);
        },
        function (e) {
            document.getElementById("output").innerHTML =
                "Failed to find any folders to copy to: " + e.message;
        });
    }

function copyToFolder(folderList, currentIndex, sourceFile) {
    if (currentIndex === folderList.length) {
        document.getElementById("output").innerHTML =
            "Failed to find a writable folder to copy to";
        return;
    }

    var destinationFolder = folderList[currentIndex];
    document.getElementById("output").innerHTML =
            "Trying folder: " + destinationFolder.name + "...";
    performCopyToDevice(
            destinationFolder,
            sourceFile,
            function (newFile) {
        document.getElementById("output").innerHTML += "Created file: " +
        newFile.name + " in folder: " + destinationFolder.name + "<br/>";
    },
        function (e) {
        copyToFolder(folderList, currentIndex + 1, sourceFile);
    });
}

    function performCopyToDevice(
        destinationFolder, sourceFile, completedHandler, errorHandler) {
        if (itemInFileSystemStorage(destinationFolder)) {
            sourceFile.copyAsync(destinationFolder).then(
                completedHandler, errorHandler);
        } else {
            // Use createFile/stream copy for non-file-system-based storages
            var destOutputStream = null;
            var newFile = null;
            return destinationFolder.createFileAsync(sourceFile.fileName).
                then(
                    function (file) {
                newFile = file;
                return newFile.openAsync(
                    Windows.Storage.FileAccessMode.readWrite);
            },
                    errorHandler).
                then(
                    function (destStream) {
                destOutputStream = destStream.getOutputStreamAt(0);
                return sourceFile.openForReadAsync();
            },
                    errorHandler).
                then(
                    function (sourceInputStream) {
                Windows.Storage.Streams.RandomAccessStream.copy(
                    sourceInputStream, destOutputStream);
                return destOutputStream.flushAsync();
            },
                    errorHandler).
                then(
                    function () {
                completedHandler(newFile);
            },
                    errorHandler);
        }
    }

    function itemInFileSystemStorage(item) {
        // Items in file-system-backed storages have a non-zero-length path
        return (item.path.length > 0);
    }
</script>
</head>
<body>
<p>
Click "Send  File" <br /> </p>

<input type="button" onclick="pickStorage()" 
       value="Pick and Send File to Storage" /><br />
<div id=output></div>

</body>
</html>  
 


5. Test the Application

  1. Plug in your removable storage device, if it isn't already attached.
  2. On the Debug menu, click Start Debugging to test the solution.
  3. Click the Pick and Send File to Storage button to pick a file using the FilePicker and copy the file to the removable storage device.

Note  If you get an error, check the following:

  • Make sure you've enabled access to removable storage by opening package.appxmanifest in Solution Explorer and checking Removable Storage in the Capabilities tab.

Summary

You've learned how to copy local files to a removable storage devices. In the next tutorial, you'll learn to get an image file from a removable storage device and display it.

Related topics

Quickstart: Enumerating Common Devices
Access the SD card in Windows Phone apps

 

 

Show:
© 2014 Microsoft