Bagikan melalui


Quickstart: Accessing files with file pickers(HTML)

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

Access files and folders through the file picker by letting users pick files and folders. You can use the fileOpenPicker class to gain access to files and the folderPicker to gain access to folders.

Prerequisites

File picker UI

File pickers have areas at the top and bottom of the screen that display information, to orient users and provide a consistent experience when users access or save files.

The displayed information includes:

  • The current location, which is in the upper left
  • A basket of items that the user chose, which is along the bottom
  • A drop-down list of locations that the user can browse, which can be selected from the down-caret in the upper left

For example, this screen shot shows a file picker that was called to let the user choose some files. In the screen shot, the user has selected two files. A screen capture of the file picker with two files selected to be opened.

The user can view the drop-down list of available locations, like the list shown in the screen shot on the right, by selecting the down-caret in the upper left of the file picker. These locations include file system locations, like the Music or Downloads folder. They also include other apps, if these other apps (like Microsoft OneDrive) participate file picker contracts , which you can see at the bottom of the list in the screen shot.

A cropped screen capture of the file picker that shows the dropdown list of locations in the upper left.

 

Complete code to pick one file

The File picker sample demonstrates how to use fileOpenPicker to let the user pick a single file.

// Create the picker object and set options
var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail;
openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.picturesLibrary;
// Users expect to have a filtered view of their folders depending on the scenario.
// For example, when choosing a documents folder, restrict the filetypes to documents for your application.
openPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg"]);

// Open the picker for the user to pick a file
openPicker.pickSingleFileAsync().then(function (file) {
    if (file) {
        // Application now has read/write access to the picked file
        WinJS.log && WinJS.log("Picked photo: " + file.name, "sample", "status");
    } else {
        // The picker was dismissed with no selected file
        WinJS.log && WinJS.log("Operation cancelled.", "sample", "status");
    }
});

For the complete code to pick multiple files, see the File picker sample.

Walkthrough for picking one file

Calling the file picker requires two basic tasks: creating and customizing a file picker object, and showing the file picker so the user can pick an item or items.

  1. Create and customize a fileOpenPicker

    Use fileOpenPicker if the user is picking one or more files. You can customize this class by setting properties on the object you create.

    The File picker sample demonstrates how to create and customize a fileOpenPicker.

    // Create the picker object and set options
    var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
    openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail;
    openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.picturesLibrary;
    // Users expect to have a filtered view of their folders depending on the scenario.
    // For example, when choosing a documents folder, restrict the filetypes to documents for your application.
    openPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg"]);
    

    You should set the properties on the file picker object that are relevant to your users and your app. For guidelines to help you decide how to customize the file picker, see Guidelines and checklist for file pickers. For explanations of why we set certain properties to customize the file pickers in the File picker sample, continue reading.

    File picker sample fileOpenPicker customizations, explained

    The File picker sample creates a rich, visual display of pictures in a convenient location that the user can pick from by setting three fileOpenPicker properties: viewMode, suggestedStartLocation, and fileTypeFilter properties.

    • Setting openPicker.viewMode to the thumbnail PickerViewMode enum value creates a rich, visual display by using picture thumbnails to represent files in file picker.

      openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail;
      

      You should consider setting viewMode to PickerViewMode.thumbnail if you are using the file picker to display visual files like pictures or videos. Otherwise, use PickerViewMode.list.

      In some cases, the user may want to pick a picture or video or any other kind of file. For example, the user may be picking a file to attach to an email or to send via IM. In this case, you should support both view modes by adding two UI controls to your app. One control should call the file picker by using the thumbnail view mode, so that the user can pick pictures and videos. The other control should call the file picker by using the list view mode, so that the user can pick other kinds of files. For example, a mail app would have two buttons: Attach Picture or Video and Attach Document.

    • Setting openPicker.suggestedStartLocation to Pictures using PickerLocationId.picturesLibrary lets the user start in a location where they are likely to find pictures.

      openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.picturesLibrary;
      

      You should set suggestedStartLocation to file system location that is appropriate for the type of file that is being picked. If the user is picking music, pictures, or videos, set the start location to Music, Pictures, or Videos respectively. For all other types of files, set the start location to Documents. This is just a starting location. Users can navigate to other locations while they are using the file picker.

      Additionally, the suggestedStartLocation is not always used as the start location for the file picker. To give the user a sense of consistency, the file picker remembers the last location that the user viewed and will generally start at that location.

    • Using openPicker.fileTypeFilter.replaceAll to specify the types of files that the user can see in the file picker lets us keep the user focused on picking files that are relevant and usable.

      openPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg"]);
      

      You should consider specifying the types of files to display in the file picker to help keep the files that are displayed relevant. For example, if your app is a video player, you can use the fileTypeFilter property to ensure that the files displayed in the file picker are in video formats that your player supports, based on the video file name extension.

      If you want to add file types to the fileTypeFilter instead of replacing entries, you can use the append method instead of replaceAll.

  2. Show the fileOpenPicker

    You can now show the file picker so that the user can pick either a single file or multiple files:

    • Show so the user can pick a single file

      After you create and customize the file picker, let the user pick one file by calling fileOpenPicker.pickSingleFileAsync. When the user picks a file, fileOpenPicker.pickSingleFileAsync returns a storageFile object that represents the picked file.

      The File picker sample demonstrates how to display the file picker to let the user pick one file, and how to capture the picked file for processing.

      // Open the picker for the user to pick a file
      openPicker.pickSingleFileAsync().then(function (file) {
          if (file) {
              // Application now has read/write access to the picked file
              WinJS.log && WinJS.log("Picked photo: " + file.name, "sample", "status");
          } else {
              // The picker was dismissed with no selected file
              WinJS.log && WinJS.log("Operation cancelled.", "sample", "status");
          }
      });
      

      When the openPicker.pickSingleFileAsync call completes, the picked file, which is represented by a storageFile object, is passed to a function literal for processing as the file parameter. If the operation was canceled and nothing was picked, this parameter will be null.

    • Show so the user can pick a multiple files

      After you create and customize a file picker, let the user pick multiple files by calling fileOpenPicker.pickMultipleFilesAsync.

      When the user picks multiple files, fileOpenPicker.pickMultipleFilesAsync returns a list of storageFile objects that represent the picked files.

      The File picker sample demonstrates how to display the file picker to let the user pick multiple files, and how to capture the list of picked files for processing.

      openPicker.pickMultipleFilesAsync().then(function (files) {
          if (files.size > 0) {
              // Application now has read/write access to the picked file(s)
              var outputString = "Picked files:\n";
              for (var i = 0; i < files.size; i++) {
                  outputString = outputString + files[i].name + "\n";
              }
              WinJS.log && WinJS.log(outputString, "sample", "status");
          } else {
              // The picker was dismissed with no selected file
              WinJS.log && WinJS.log("Operation cancelled.", "sample", "status");
          }
      });
      

      When the openPicker.pickMultipleFilesAsync call completes, the list of picked files is passed to a function literal for processing as the files parameter. The picked files in the list are represented by storageFile objects. If the operation was canceled and nothing was picked, this parameter will have a size greater than 0.

Complete code to pick one folder

The File picker sample demonstrates how to use folderPicker to let the user pick a single folder.

// Verify that we are currently not snapped, or that we can unsnap to open the picker
var currentState = Windows.UI.ViewManagement.ApplicationView.value;
if (currentState === Windows.UI.ViewManagement.ApplicationViewState.snapped &&
    !Windows.UI.ViewManagement.ApplicationView.tryUnsnap()) {
    // Fail silently if we can't unsnap
    return;
}

// Create the picker object and set options
var folderPicker = new Windows.Storage.Pickers.FolderPicker;
folderPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.desktop;
// Users expect to have a filtered view of their folders depending on the scenario.
// For example, when choosing a documents folder, restrict the filetypes to documents for your application.
folderPicker.fileTypeFilter.replaceAll([".docx", ".xlsx", ".pptx"]);

folderPicker.pickSingleFolderAsync().then(function (folder) {
    if (folder) {
        // Application now has read/write access to all contents in the picked folder (including sub-folder contents)
        // Cache folder so the contents can be accessed at a later time
        Windows.Storage.AccessCache.StorageApplicationPermissions.futureAccessList.addOrReplace("PickedFolderToken", folder);
        WinJS.log && WinJS.log("Picked folder: " + folder.name, "sample", "status");
    } else {
        // The picker was dismissed with no selected file
        WinJS.log && WinJS.log("Operation cancelled.", "sample", "status");
    }
});

Walkthrough for picking one folder

Calling the file picker requires two basic tasks: create and customize a file picker object, and show the file picker so the user can pick an item or items.

  1. Create and customize a folderPicker

    Use folderPicker if the user is picking a folder. You can customize this class by setting properties on the object you create.

    The File picker sample demonstrates how to create and customize a folderPicker.

    // Create the picker object and set options
    var folderPicker = new Windows.Storage.Pickers.FolderPicker;
    folderPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.desktop;
    // Users expect to have a filtered view of their folders depending on the scenario.
    // For example, when choosing a documents folder, restrict the filetypes to documents for your application.
    folderPicker.fileTypeFilter.replaceAll([".docx", ".xlsx", ".pptx"]);
    

    You should set the properties on the file picker object that are relevant to your users and your app. For guidelines to help you decide how to customize the file picker, see Guidelines and checklist for file pickers. For explanations of why we set certain properties to customize the file pickers in the File picker sample, continue reading.

    File picker sample folderPicker customizations, explained

    The File picker sample customizes the file picker to pick folders by using three folderPicker properties: viewMode, suggestedStartLocation, and fileTypeFilter properties.

    • Using the default PickerViewMode.list for the folderPicker.viewMode lets us create a list-like display in the file picker. This list is good for selecting files that are not very visual, like documents.

      You should consider setting viewMode to PickerViewMode.thumbnail if you are using the file picker to display visual files like pictures or videos. Otherwise, use PickerViewMode.list.

      If you are displaying visual files like pictures or videos, you should set the folderPicker.viewMode to the thumbnail like this:

      folderPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail;
      
    • Setting folderPicker.suggestedStartLocation to the user's desktop using PickerLocationId.desktop lets the user start in a familiar, highly used location.

      folderPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.desktop;
      

      You should set suggestedStartLocation to file system location that is appropriate for type of folder that the user wants to pick. For example, if the user is picking a folder that contains music files, you should start them in Music. This is just a starting location; users can navigate to other locations while they are using the file picker.

      Additionally, the suggestedStartLocation is not always used as the start location for the file picker. To give the user a sense of consistency, the file picker remembers the last location that the user viewed and will generally start at that location.

    • Using folderPicker.fileTypeFilter.replaceAll to specify the types of files that the user can see in the file picker lets us keep the user focused on picking a relevant folder.

      folderPicker.fileTypeFilter.replaceAll([".docx", ".xlsx", ".pptx"]);
      

      Users can only select folders through a folderPicker, they will not be able to select individual files. However, showing relevant files in the folderPicker helps users determine which folder they want to select. For example, when using the folderPicker to select a location to import pictures from, showing image files helps the user identify what items will be imported when the location is selected.

  2. Show the folderPicker so the user can pick a single folder

    After you create and customize a folderPicker, let the user pick a folder by calling folderPicker.pickSingleFolderAsync. When the user picks a folder, folderPicker.pickSingleFolderAsync returns a storageFolder that represents the picked folder. You should capture and process this folder using done so that exceptions propagate properly.

    The File picker sample demonstrates how to display the file picker to let the user pick a folder, and how to capture the picked folder for processing.

    folderPicker.pickSingleFolderAsync().then(function (folder) {
        if (folder) {
            // Application now has read/write access to all contents in the picked folder (including sub-folder contents)
            // Cache folder so the contents can be accessed at a later time
            Windows.Storage.AccessCache.StorageApplicationPermissions.futureAccessList.addOrReplace("PickedFolderToken", folder);
            WinJS.log && WinJS.log("Picked folder: " + folder.name, "sample", "status");
        } else {
            // The picker was dismissed with no selected file
            WinJS.log && WinJS.log("Operation cancelled.", "sample", "status");
        }
    });
    

    When the folderPicker.pickSingleFolderAsync call completes, the picked folder is passed to a function literal for processing as the folder parameter. The picked folder is represented by a storageFolder object. If the operation was canceled and nothing was picked, this parameter will be null.

Summary and next steps

If you use code similar to what is shown here, your app will display a file picker that lets users pick one or more files or folders that your app can then open.

Tip  Whenever your app accesses a file or folder through the file picker, add that item to your app's futureAccessList or mostRecentlyUsedList to keep track of it. You can learn more about using these lists in How to track recently used files and folders.

 

To learn about reading and writing files, see Quickstart: Reading and writing a file and the File access sample. To learn about working with image files, see How to select and display an image, How to decode an image, and the Using a Blob to save and load content sample.

If you want to learn about calling the file picker to save files, see How to save files through file pickers.

If you want your app to provide files, a save location, or file updates to other apps, see Quickstart: Integrating with file picker contracts.

File picker sample

File access sample

Using a Blob to save and load content sample

Guidelines and checklist for file pickers

How to save files through file pickers

How to track recently used files and folders

Quickstart: Reading and writing a file

How to select and display an image

Quickstart: Providing services with file pickers

Reference

Windows.Storage.Pickers namespace

Windows.Storage.Pickers.fileOpenPicker class

Windows.Storage.Pickers.folderPicker class

Windows.Storage.Pickers.pickerLocationId enum

Windows.Storage.Pickers.pickerViewMode enum