다음을 통해 공유


빠른 시작: 저장 장치에 파일 보내기(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 카드 액세스