Guida introduttiva: Invio di un file a un dispositivo di archiviazione (HTML)
[ Questo articolo è rivolto agli sviluppatori per Windows 8.x e Windows Phone 8.x che realizzano app di Windows Runtime. Gli sviluppatori che usano Windows 10 possono vedere Documentazione aggiornata ]
Questa esercitazione mostra come copiare un file in un dispositivo di archiviazione rimovibile creando un'istanza di un oggetto di archiviazione mediante Windows.Devices.Portable.Storage.FromId.
Obiettivo: Imparerai a usare l'API Windows.Devices.Enumeration per enumerare i dispositivi di archiviazione rimovibili e sceglierne uno da usare per creare un'istanza di un oggetto di archiviazione, che potrà quindi essere usato come destinazione di un'operazione copyAsync.
Prerequisiti
Devi conoscere già JavaScript e HTML.
Devi avere a disposizione un dispositivo di archiviazione rimovibile.
Tempo per il completamento: 20 minuti.
Istruzioni
1. Aprire Microsoft Visual Studio
Apri un'istanza di Visual Studio.
2. Creare un nuovo progetto
Nella finestra di dialogo Nuovo progetto scegli un'applicazione vuota dai tipi di progetto JavaScript.
3. Dichiarare la funzionalità Archivi rimovibili
Fai doppio clic su package.appxmanifest in Esplora soluzioni. Fai clic sulla scheda Funzionalità. Seleziona Archivio rimovibile nell'elenco Funzionalità.
4. Inserire il codice JavaScript e HTML dell'applicazione
Apri il file Default.html e copia al suo interno il codice HTML seguente, sostituendo il contenuto originale.
<!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. Testare l'applicazione
- Collega il dispositivo di archiviazione rimovibile, se non lo hai ancora fatto.
- Scegli Avvia debug dal menu Debug per testare la soluzione.
- Fai clic sul pulsante Seleziona e invia file ad archivio per selezionare un file mediante Selezione file e copiarlo nel dispositivo di archiviazione rimovibile.
Nota Se ricevi un errore, procedi come segue:
- Verifica di avere abilitato l'accesso all'archivio rimovibile aprendo package.appxmanifest in Esplora soluzioni e controllando che l'opzione Archivio rimovibile nella scheda Funzionalità sia selezionata.
Riepilogo
In questa esercitazione hai appreso come copiare file locali in un dispositivo di archiviazione rimovibile. Nella prossima esercitazione imparerai a recuperare un file di immagine da un dispositivo di archiviazione rimovibile e a visualizzarlo.
Argomenti correlati
Guida introduttiva: Enumerazione dei dispositivi di uso comune