快速入門:將檔案傳送到存放裝置 (HTML)
[ 本文的目標對象是撰寫 Windows 執行階段 App 的 Windows 8.x 和 Windows Phone 8.x 開發人員。如果您正在開發適用於 Windows 10 的 App,請參閱 最新文件 ]
這個教學課程說明如何使用 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. 測試應用程式
- 如果卸除式存放裝置尚未接到電腦,現在請接上。
- 在 [偵錯]**** 功能表中按一下 [開始偵錯] 來測試方案。
- 按一下 [挑選並將檔案傳送到儲存區]**** 按鈕,使用 FilePicker 挑選檔案,然後將檔案複製到卸除式存放裝置。
注意 如果您收到錯誤,請檢查下列項目:
- 藉由在 [方案總管] 中開啟 package.appxmanifest 並檢查 [功能] 索引標籤中的 [卸除式存放裝置]****,來確定已啟用存取卸除式存放裝置。
摘要
您現在已學會如何將本機檔案複製到卸除式存放裝置。 在下一個教學課程中,您將學習如何從卸除式存放裝置取得影像檔,並加以顯示。