快速入门:向存储设备发送一个文件 (HTML)

[ 本文适用于编写 Windows 运行时应用的 Windows 8.x 和 Windows Phone 8.x 开发人员。如果你要针对 Windows 10 进行开发,请参阅 最新文档 ]

本教程介绍如何通过使用 Windows.Devices.Portable.Storage.FromId 实例化一个存储对象将文件复制到可移动存储设备。

目标: 你将了解如何使用 Windows.Devices.Enumeration API 来枚举可移动存储设备,并选择其中一个设备用于实例化存储对象,此存储对象可用作 copyAsync 操作的目标。

先决条件

你应该熟悉 JavaScript 和 HTML。

你需要有一个可移动的存储设备。

完成所需时间: 20 分钟.

说明

1. 打开 Microsoft Visual Studio

打开 Visual Studio 的一个实例。

2. 创建一个新项目

在“新建项目”对话框中,从 JavaScript 项目类型中选择一个空白应用程序。

3. 声明可移动存储功能

在解决方案资源管理器中,双击“package.appxmanifest”。选择“功能”选项卡。在“功能”列表中选中“可移动存储”

4. 插入应用程序 JavaScript 和 HTML

打开 Default.html,将以下 HTML 复制到此文件中,并替换掉原来的内容。


  
<!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. 测试应用程序

  1. 如果你的可移动存储设备未连接,请将其插入。
  2. 在“调试”****菜单上,单击“启动调试”测试该解决方案。
  3. 单击“选取文件并发送到存储”****按钮以使用文件选取器选取文件,然后将文件复制到可移动存储设备。

注意  如果出错,请检查以下内容:

  • 确保已启用对可移动存储的访问权限,方法是在解决方案资源管理器中打开 package.appxmanifest 并在“功能”****选项卡中选中“可移动存储”。

 

摘要

你已经了解了如何将本地文件复制到可移动存储设备。 在下一教程中,你将了解如何从可移动存储设备获取图像文件并显示它。

相关主题

快速入门:枚举通用设备

在 Windows Phone 应用中访问 SD 卡