Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use file picker to access files in JavaScript

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to use file picker to access files in JavaScript", the content of the explanation in the article is simple and clear, easy to learn and understand, please follow the editor's ideas slowly in-depth, together to study and learn "how to use file picker to access files in JavaScript"!

Use the file picker to access files and folders by letting the user select them. You can use the fileOpenPicker class to get access to files and folderPicker to get access to folders.

Prerequisites

Understand the asynchronous programming of Windows App Store applications in JavaScript

Learn how to write asynchronous applications in using promises in JavaScript.

File picker UI

The file picker has areas that display information at the top and bottom of the screen to direct users and provide a consistent experience when users access or maintain files.

The information displayed includes:

Current position (in the upper left corner)

User-selected item basket (along the bottom)

Drop-down list of locations that users can browse (can be selected from the drop-down symbol in the upper left corner)

For example, this screenshot shows a file picker that has been called, with which users can select certain files. In this screenshot, the user has selected two files.

Users can view a drop-down list of available locations by selecting the drop-down symbol in the upper-left corner of the file picker, such as the list shown in the screenshot on the right. These locations contain file system locations, such as Music Library or download folders. They also include other applications (if these applications (such as Microsoft SkyDrive) participate in file picker contracts, you can see them at the bottom of the list in the screenshot.

Complete the code to select a file

The file picker example shows how to use fileOpenPicker to let the user select a single file.

/ / 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 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 complete code for selecting multiple files, see the file picker example.

If Warning tries to display the file picker while your application is attached, the file picker will not be displayed and an exception will be thrown. This can be avoided by ensuring that the application is not attached or unattached before calling the file picker. The following code examples and file picker examples show how to do this.

Select a file for the walkthrough

Invoking the file picker requires three basic tasks: ensuring that the file picker can be called, creating and customizing the file picker object, and displaying the file picker so that the user can select one or more items.

1. Make sure you can call the file picker

Every time you need to call the file picker, you must first make sure that your application can display the file picker. This can be done in two ways: make sure your application is not attached, or if your application is already attached, unattach to display the file picker.

The file picker example shows how to check the applied ApplicationView.value and try to unattach before the example creates and displays the file picker.

/ / 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;}

If Warning tries to display a file picker while your application is attached, the call will fail and you will encounter an exception.

two。 Create and customize fileOpenPicker

If the user picks up one or more files, use fileOpenPicker. You can customize this class by setting properties on the object you create.

The file picker example shows 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 properties related to your users and your application on the file picker object. For guidelines to help you determine how to customize the file picker, see the file picker guide and list. Read on for an explanation of why we set some properties to customize the file picker in the file picker example.

File picker sample fileOpenPicker customization, described

The file picker example creates a rich visual display of pictures in a convenient location that users can select from by setting the following three fileOpenPicker properties: viewMode, suggestedStartLocation, and fileTypeFilter properties.

Setting openPicker.viewMode to the thumbnail PickerViewMode enumeration value represents the files in the file picker by creating a rich visual display using picture thumbnails.

OpenPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail

If you use a file picker to display visual files such as pictures or videos, you should consider setting viewMode to PickerViewMode.thumbnail. Otherwise, use PickerViewMode.list.

In some cases, the user may need to select a picture or video, or any other kind of file. For example, a user might select a file to attach to an e-mail message or send it over IM. In this case, you should support both view modes at the same time by adding two UI controls to your application. A control should invoke the file picker by using thumbnail view mode so that the user can select pictures and videos. Another control should invoke the file picker by using list view mode so that the user can select other kinds of files. For example, a mail application will have two buttons: "attach picture or video" and "attach document".

Setting openPicker.suggestedStartLocation as a picture library using PickerLocationId.picturesLibrary allows users to start somewhere where they are likely to find the picture.

OpenPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.picturesLibrary

You should set suggestedStartLocation to fit the file system location of the selected file type. If the user wants to select music, picture, or video, set the start location to the music library, picture library, or video library, respectively. For all other types of files, set the start location to the document library. This is just a starting position. Users can navigate to other locations when using the file picker.

In addition, suggestedStartLocation is not always used as the starting position of the file picker. To give the user a sense of consistency, the file picker remembers the last location the user viewed and usually starts there.

Using openPicker.fileTypeFilter.replaceAll to specify the file types that the user can see in the file picker allows us to keep the user focused on selecting relevant and available files.

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

You should consider specifying the file types to be displayed in the file picker to help keep the displayed files relevant. For example, if your application is a video player, you can use the fileTypeFilter attribute to ensure that the files displayed in the file picker use the video format supported by your player, based on the video file name extension.

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

3. Show fileOpenPicker

You can now display the file picker so that the user can select a single file or multiple files:

Display so that the user can select a single file

After you create and customize the file picker, let the user select a file by calling fileOpenPicker.pickSingleFileAsync. When the user selects a file, fileOpenPicker.pickSingleFileAsync returns a storageFile object that represents the selected file.

The file picker example shows how to display a file picker to allow the user to select a file, and how to capture the selected 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 is complete, the selected file (represented by the storageFile object) is passed to the function text for processing as a file parameter. If the operation is canceled and no objects are selected, this parameter will be null.

Display so that users can select multiple files

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

When a user selects multiple files, fileOpenPicker.pickMultipleFilesAsync returns a list of storageFile objects that represent multiple files that have been selected.

The file picker example shows how to display a file picker to allow users to select multiple files, and how to capture a list of selected 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; iTunes +) {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 is complete, the list of selected files is passed to the function text for processing as a files parameter. The selected files in the list are represented by the storageFile object. If the operation is canceled and no objects are selected, the size of this parameter will be greater than 0

Complete the code to select a folder

The file picker example shows how to use folderPicker to let the user select 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");}})

If Warning tries to display the file picker while your application is attached, the file picker will not be displayed and an exception will be thrown. This can be avoided by ensuring that the application is not attached or unattached before calling the file picker. The following code examples and file picker examples show how to do this.

The process of selecting a folder

Invoking the file picker requires three basic tasks: ensuring that the file picker can be called, creating and customizing the file picker object, and displaying the file picker so that the user can select one or more items.

1. Make sure you can call the file picker

Every time you need to call the file picker, you must first make sure that your application can display the file picker. This can be done in two ways: make sure your application is not attached, or if your application is already attached, make sure you can unattach it to display the file picker.

The file picker example shows how to check the applied ApplicationView.value and try to unattach before the example creates and displays the file picker.

/ / 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;}

If Warning tries to display a file picker while your application is attached, the call will fail and you will encounter an exception.

two。 Create and customize folderPicker

If the user picks up a folder, use folderPicker. You can customize this class by setting properties on the object you create.

The file picker example shows 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 properties related to your users and your application on the file picker object. For guidelines to help you determine how to customize the file picker, see the file picker guide and list. Read on for an explanation of why we set some properties to customize the file picker in the file picker example.

File picker sample FolderPicker customization, described

The file picker example customizes the file picker by using the following three folderPicker properties to select folders: viewMode, suggestedStartLocation, and fileTypeFilter properties.

Using the default PickerViewMode.list for folderPicker.viewMode allows us to create a similar list display in the file picker. This list is suitable for selecting files that are not very intuitive, such as the following documents.

If you use a file picker to display visual files such as pictures or videos, you should consider setting viewMode to PickerViewMode.thumbnail. Otherwise, use PickerViewMode.list.

If you want to display visual files such as pictures or videos, you should set folderPicker.viewMode to thumbnail, such as:

FolderPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail

Setting folderPicker.suggestedStartLocation as the user's desktop using PickerLocationId.desktop allows the user to start at a familiar, highly used location.

FolderPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.desktop

You should set suggestedStartLocation to fit the file system location of the folder type that the user wants to choose. For example, if the user wants to select a folder that contains music files, you should start them in the music library. This is just a starting location; users can navigate to other locations when using the file picker.

In addition, suggestedStartLocation is not always used as the starting position of the file picker. To give the user a sense of consistency, the file picker remembers the last location the user viewed and usually starts there.

Using folderPicker.fileTypeFilter.replaceAll to specify the file types that the user can see in the file picker allows us to keep the user focused on selecting the relevant folder.

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

A user can select a folder only through folderPicker, and he will not be able to select a single file. However, displaying related files in folderPicker can help users determine which folder they need to choose. For example, when you use folderPicker to select a location from which you want to import a picture, displaying an image file can help you determine which items will be imported when you select that location.

3. Displays the folderPicker so that users can select a single folder

After you create and customize the folderPicker, let the user select a folder by calling folderPicker.pickSingleFolderAsync. When the user selects a folder, folderPicker.pickSingleFolderAsync returns a storageFolder that represents the selected file. You should use done to capture and process this folder so that these exceptions will propagate correctly.

The file picker example shows how to display a file picker to allow the user to select a folder, and how to capture the selected 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 is complete, the selected folder is passed to the function text to be processed as a folder parameter. The selected folder is represented by a storageFolder object. If the operation is canceled and no objects are selected, this parameter will be null.

Thank you for reading, the above is the content of "how to use file picker to access files in JavaScript". After the study of this article, I believe you have a deeper understanding of how to use file picker to access files in JavaScript, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report