다음을 통해 공유


빠른 시작: 저장 장치에서 이미지 파일 가져오기(HTML)

[ 이 문서는 Windows 런타임 앱을 작성하는 Windows에서 8.x 및 Windows Phone 8.x 개발자를 대상으로 합니다. Windows 10용으로 개발하는 경우에는 최신 설명서를 참조하세요.]

이 자습서는 이동식 저장 장치에서 이미지 파일을 가져와 표시하는 방법을 소개합니다.

목표: 이전의 예제처럼 휴대용 저장 장치를 열거하고 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. 지원되는 파일 형식 상자에서 새로 추가를 클릭하고 파일 형식 필드에 .gif라고 입력하여 .gif를 지원되는 파일 형식으로 추가합니다.
  4. 새로 추가를 클릭하고 파일 형식에 .jpg 및 .png를 입력하여 지원되는 파일 형식을 두 개 더 추가합니다.

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에서 장치 ID를 가져와 Windows.Devices.Portable.Storage.FromId로 전달하여 저장소 개체를 만든 후에 저장 장치의 이미지에 액세스했습니다.

이 예제는 successHandler 함수에서 열거된 모든 저장 장치 중 첫 번째를 선택했지만, 앱을 수정하여 사용 가능한 모든 이동식 저장소를 나열하고 사용자가 선택하게 할 수 있습니다.

다음 자습서에서는 자동 실행 처리기를 사용하여 저장소 개체를 만듭니다.

관련 항목

빠른 시작: 일반적인 장치 열거

Windows Phone 앱에서 SD 카드 액세스