次の方法で共有


クイック スタート: 記憶装置へのファイルの送信 (HTML)

このチュートリアルでは、Windows.Devices.Portable.Storage.FromId を使ってストレージ オブジェクトをインスタンス化し、リムーバブル記憶装置にファイルをコピーする方法について説明します。

目標: Windows.Devices.Enumeration API を使ってリムーバブル記憶装置を列挙し、そこから 1 つ選んでストレージ オブジェクトをインスタンス化して、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. [Pick and Send File to Storage] (ファイルを選んでストレージに送る) ボタンをクリックし、ファイル ピッカーを使ってファイルを選び、リムーバブル記憶装置にコピーします。

  エラーが発生した場合は、次の点を確認してください。

  • リムーバブル ストレージへのアクセスが有効になっていることを確認します。ソリューション エクスプローラーで package.appxmanifest を開き、[機能] タブの [リムーバブル ストレージ] を確認してください。

 

要約

ローカル ファイルをリムーバブル記憶装置にコピーする方法について説明しました。 次のチュートリアルでは、リムーバブル記憶装置から画像ファイルを取得して表示する方法について説明します。

関連トピック

クイック スタート: 一般的なデバイスの列挙

Windows Phone アプリでの SD カードへのアクセス