Краткое руководство: отправка файла на запоминающее устройство (HTML)
[ Эта статья адресована разработчикам приложений среды выполнения Windows для Windows 8.x и Windows Phone 8.x. При разработке приложений для Windows 10 см. раздел последняя документация]
В этом учебнике показано, как скопировать файл на съемное запоминающее устройство, создав экземпляр объекта хранилища с помощью Windows.Devices.Portable.Storage.FromId.
Цель: Вы узнаете, как использовать API Windows.Devices.Enumeration, чтобы перечислить съемные запоминающие устройства и выбрать одно из них для создания экземпляра объекта хранилища, который можно будет использовать как целевой объект операции 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. Проверка приложения
- Подключите съемное ЗУ, если оно еще не подключено.
- Чтобы проверить решение, в меню Отладка щелкните Начать отладку.
- Нажмите кнопку Выбрать файл и отправить на устройство, чтобы с помощью средства выбора файлов выбрать файл, а затем скопировать его на съемное запоминающее устройство.
Примечание Если вы получили ошибку, проверьте следующее.
- Убедитесь, что вы разрешили доступ к съемным носителям: откройте файл package.appxmanifest в обозревателе решений и проверьте состояние возможности Съемные носители на вкладке Возможности.
Сводка
Вы научились копировать локальные файлы на съемные запоминающие устройства. В следующем учебнике будет показано, как получить файл изображения со съемного носителя и отобразить его.