current position:Home>File upload can be triggered without using file type input

File upload can be triggered without using file type input

2021-08-26 12:32:48 Xin space

 Folder pictures

One 、 Consider the past you shall know the future

Tradition in Web End file upload , Is to use file Type of form input box :

<input type="file">

file input box

We can go through accept Property specifies the file type selected ,directory Property specifies whether a folder can be selected ,capture Property to specify the front or rear camera .

The function is still very strong .

See my previous article for details :“HTML input type=file File selection two or three things

however file The input box has a fatal drawback , Namely UI Too ugly , And you can't customize .

Although the use of <label> Element can simulate clicking a button , adopt for Attribute points to file input Achieve a similar effect , But it's a little wordy .

Is there any way to click an ordinary button , It can also trigger file selection ? It's best to set and select folders or files , Set the selected file format type .

There are , modern Web Continuous development , A new API, be called File System Access API, You can click any element to trigger file selection .

Two 、showOpenFilePicker Method

Suppose there is a button on the page , Its HTML As shown below :

<button id="button"> Select Picture </button>

Then the following lines JavaScript Code can be achieved by clicking the button to display the file selection :

button.addEventListener('click', function () {
    //  Open file 
    window.showOpenFilePicker();
});

It's so simple and rough , Directly when .

Of course , We can also use showDirectoryPicker() Method to select a folder .

button.addEventListener('click', function () {
    //  Open folder 
    window.showDirectoryPicker();
});

Because of two API Parameters and functions are similar , Therefore, only the selection of documents is described in detail .

file type 、 Specify whether to select multiple items

showOpenFilePicker(options) Method can pass parameters , The specific parameters supported are as follows :

among ,options Is an optional parameter , The following properties are supported :

multiple
Boolean value , The default value is false , Indicates that only one file can be selected .
excludeAcceptAllOption
Boolean value , The default value is false , Indicates whether to exclude the following types All of them accept file type .
types
An array of selectable file types , Each array item is also an object , The following two parameters are supported :

  • description: Represents the description of a file or folder , character string , Optional .
  • accept: Type of documents accepted , object , Then the key of the object is the key of the file MIME matching , Values are arrays , Indicates the supported file suffix . For details, see the following diagram .

For example, the following JS Code execution is to select multiple local desktop images at one time :

window.showOpenFilePicker({
    types: [{
        description: 'Images',
        accept: {
            'image/*': ['.png', '.gif', '.jpeg', '.jpg', '.webp']
        }
    }],
    //  You can select multiple pictures 
    multiple: true
});

3、 ... and 、 demonstration - Click the button to select and display multiple images

It is known that the selection file , But how to deal with the selected file , Here's an example , It will be very helpful for everyone to study .

The complete code is as follows :

<button id="button"> Select Picture </button>
<p id="output"></p>
button.addEventListener('click', async function () {
    //  Open file 
    const arrFileHandle = await window.showOpenFilePicker({
        types: [{
            accept: {
                'image/*': ['.png', '.gif', '.jpeg', '.jpg', '.webp']
            }
        }],
        //  You can select multiple pictures 
        multiple: true
    });
    
    //  Traverse the selected file 
    for (const fileHandle of arrFileHandle) {
        //  Get file content 
        const fileData = await fileHandle.getFile();
        //  Read file data 
        const buffer = await fileData.arrayBuffer();
        //  Turn into Blod url Address 
        let src = URL.createObjectURL(new Blob([buffer]));
        //  Show... On the page 
        output.insertAdjacentHTML('beforeend', `<img src="${src}">`);
    }
});

This example has a corresponding demo, You can click here : File access API Trigger picture selection demo

Click on demo The blue button on the page :

 Click the blue button

Select the corresponding picture in your computer , For example, I chose 2 Zhang good PNG picture :

 Select a screenshot of the image

It turns out that Web The picture effect is successfully previewed on the page , As shown in the screenshot below :

 Preview effect on the page

Is it with the traditional file File selection is very similar .

Because of these new API Are walking Promise, therefore , have access to async、 await Wait for new JS grammar , Avoid all kinds of messy callbacks , The code is simpler and easier to read .

Isn't that great !

Four 、 Unfortunately, it's a new API

I don't like it HTML Form Elements , like JavaScript For developers of a shuttle of code , This API Will be very close and like , however , Unfortunately , This API It's relatively new , It only came out in the second half of last year ,Safari Browsers don't support , therefore , Can't be used directly .

 Compatibility

however , Many projects have been done mix Mixed processing , That is, I wrote a JS, Supported browsers use File System Access API, Unsupported browsers still use traditional <input type="file">, For example, the project of Google Labs browser-fs-access

If it is a file save or download , You can try window.showSaveFilePicker() This API, Sometimes you can introduce , Of course , The actual development , File download must be using FileSaver.js, This file can be downloaded from the unyielding King , Benchmarking Project .

In the afternoon, I participated in a live broadcast of nuggets , Talk about writing , If you are interested, you can pay attention to , There should be video and PPT, Campaign page address This is it .

Today's itinerary just answers the question about writing time , I live this afternoon , Go fishing after the live broadcast , Go home for dinner after fishing , I wrote this article after dinner , That's how time comes , manage , Next goal , Don't sleep until you finish .

above ~

Learn one every day API, Accumulate over a long period , It will be the foundation in a few years API Giant .

Welcome to forward , Comment on , There is a mistake in the text , You are welcome to correct .

Last , Please attach MDN About File System Access API Link to :File_System_Access_API

( This is the end of this article. )

copyright notice
author[Xin space],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210826123242895n.html

Random recommended