快速入門:從存放裝置取得影像檔 (HTML)

[ 本文的目標對象是撰寫 Windows 執行階段 App 的 Windows 8.x 和 Windows Phone 8.x 開發人員。如果您正在開發適用於 Windows 10 的 App,請參閱 最新文件 ]

這個教學課程說明如何從卸除式存放裝置取得影像檔,並加以顯示。

目標: 如同先前的範例,您將列舉可攜式存放裝置,並使用 Windows.Devices.Portable.Storage.FromId 將其中一個裝置具現化,但是在這個範例中,您將使用 createFileQueryWithOption 尋找影像檔,並使用 getFilesAsync 進行擷取。

先決條件

您應該熟悉 JavaScript 和 HTML。

您需要一個卸除式存放裝置。

完成所需的時間: 20 分鐘.

指示

1. 開啟 Microsoft Visual Studio

開啟 Visual Studio 的執行個體。

2. 建立新專案

在 [新增專案] 對話方塊中,從 JavaScript 專案類型中選擇 [空白的應用程式]。

3. 宣告卸除式存放裝置功能

按兩下方案總管中的 package.appxmanifest。選取 [功能] 索引標籤。選取 [功能]**** 清單中的 [卸除式存放裝置]。

4. 宣告檔案類型

  1. 在 [宣告] 索引標籤中,從 [可用宣告]**** 選擇 [檔案類型宣告]。
  2. 在 [屬性]**** 下,將名稱屬性設定成 image
  3. 在 [支援的檔案類型] 方塊中,按一下 [加入新的],然後在 [FileType] 欄位中輸入 .gif,讓 .gif 成為支援的檔案類型。
  4. 再新增兩個支援的檔案類型 .jpg 和 .png,按一下 [加入新的],然後填入 FileType。

5. 插入應用程式 HTML 和 JavaScript

開啟 Default.html,然後將以下的程式碼複製到這個檔案中,取代原來的內容。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Get an image file from a removable storage device</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 pickStorageToGetImageFrom() {
        Enum.DeviceInformation.findAllAsync(
        Windows.Devices.Portable.StorageDevice.getDeviceSelector(),
        null).then(
            successCallback,
            errorCallback);
    }

    // Handler that's called when removable storages are found.
    // storageDevices: A collection of type
    // Windows.Devices.Enumeration.DeviceInformationCollection.
    // This example just takes the first storage found in the list.
    function successCallback(storageDevices) {
        var removableStorage = null;
        if (storageDevices.length) {
            try {
                // Create an IStorageItem from the first removable storage device
                removableStorage = Windows.Devices.Portable.StorageDevice.fromId(
                storageDevices.getAt(0).id);
                // document.getElementById("output").innerHTML = storageDevices.getAt(0).name; 
            } catch (e) {
                document.getElementById("output").innerHTML =
                "Error: " + e.message;
            }
            if (removableStorage != null) {
                getImageFiles(removableStorage);
            }
        } else {
            document.getElementById("output").innerHTML =
                "No removable storage devices were found.";
        }
    }

    // Error callback that's called if unable to enumerate all 
    // removable storages
    function errorCallback(e) {
        document.getElementById("output").innerHTML =
            "Error enumerating storages: " + e.message;
    }

    // Find the images on the removable storage and display the first one
    // in the <img> element.
    // storageItem: the item representing the removable storage
    function getImageFiles(removableStorage)
    {
        // Construct the query for image files
        var queryOptions = new Windows.Storage.Search.QueryOptions(
                    Windows.Storage.Search.CommonFileQuery.orderByName,
                    [".jpg", ".png", ".gif"]);
        var imageFileQuery = removableStorage.createFileQueryWithOptions(
            queryOptions);

        // Run the query for image files
        imageFileQuery.getFilesAsync().
                    then(
                        function (items) {
            displayFirstImage(items);
        },
                        function (e) {
            document.getElementById("output").innerHTML =
                "Error when looking for images on the removable storage: "
                + e.message;
        });
    }



    function displayFirstImage(items) {
        var found = false;
        for (var i = 0, l = items.length; i < l && !found; i++) {
            if (items[i].size > 0) { // display the first non-empty file
                displayImage(items[i]);
                found = true;
            }
        }

        if (!found) {
            // No files found matching our criteria
            document.getElementById("output").innerHTML =
                "No image files found on the removable storage.";
        }
    }

    function displayImage(imageFile) {
        document.getElementById("imageNameHolder").innerHTML =
            "Image file name: " + imageFile.name + "<br/>";

        // Setting 2nd parameter to 'false' cleans up the URL 
        // after first use. we set this because we only need 
        // to load the URL into the image tag once.
        document.getElementById("imageHolder").src =
            window.URL.createObjectURL(imageFile, false);
    }
    </script>
</head>
<body>

<div>
     <p>Finds and displays the first available image file
        (.jpg, .png, or .gif) on a removable storage device.</p>
     <button onclick="pickStorageToGetImageFrom()">Get Image File</button>
</div>

<div id="output"></div>
<div id="imageOutput">
     <img id="imageHolder" alt="image holder" src=""/><br />
     <div id="imageNameHolder"></div>
</div>
</body>
</html>

6. 測試應用程式

  1. 如果卸除式存放裝置尚未接到電腦,現在請接上。
  2. 在 [偵錯]**** 功能表中按一下 [開始偵錯] 來測試方案。
  3. 按一下 [取得影像檔]**** 按鈕,以取得卸除式存放裝置上的第一個影像檔,然後將它顯示於影像元素中。

注意  如果您收到錯誤,請檢查下列項目:

  • 藉由在 [方案總管] 中開啟 package.appxmanifest 並檢查 [功能] 索引標籤中的 [卸除式存放裝置]****,來確定已啟用存取卸除式存放裝置。

 

摘要與後續步驟

在這個範例中,您會從 findAllAsync 取得裝置識別碼,然後將它傳送到 Windows.Devices.Portable.Storage.FromId 以建立儲存物件,之後再從存放裝置存取影像。

在 successHandler 函式中,這個範例選擇所有列舉存放裝置的第一個存放裝置,但是您可以修改應用程式,以顯示所有可用的卸除式存放裝置清單,供使用者選擇。

在下一個教學課程中,您將使用自動播放處理常式來建立儲存物件。

相關主題

快速入門:列舉常用的裝置

在 Windows Phone 應用程式中存取 SD 記憶卡