1# 上传文件
2
3
4Web组件支持前端页面选择文件上传功能,应用开发者可以使用[onShowFileSelector()](../reference/apis-arkweb/ts-basic-components-web.md#onshowfileselector9)接口来处理前端页面文件上传的请求,如果应用开发者不做任何处理,Web会提供默认行为来处理前端页面文件上传的请求。
5
6
7下面的示例中,当用户在前端页面点击文件上传按钮,应用侧在[onShowFileSelector()](../reference/apis-arkweb/ts-basic-components-web.md#onshowfileselector9)接口中收到文件上传请求,在此接口中开发者将上传的本地文件路径设置给前端页面。
8
9
10- 应用侧代码。
11
12  ```ts
13  // xxx.ets
14  import { webview } from '@kit.ArkWeb';
15  import { BusinessError } from '@kit.BasicServicesKit';
16  import { picker } from '@kit.CoreFileKit';
17
18  @Entry
19  @Component
20  struct WebComponent {
21    controller: webview.WebviewController = new webview.WebviewController();
22
23    build() {
24      Column() {
25        Web({ src: $rawfile('local.html'), controller: this.controller })
26          .onShowFileSelector((event) => {
27            console.log('MyFileUploader onShowFileSelector invoked');
28            const documentSelectOptions = new picker.DocumentSelectOptions();
29            let uri: string | null = null;
30            const documentViewPicker = new picker.DocumentViewPicker();
31            documentViewPicker.select(documentSelectOptions).then((documentSelectResult) => {
32              uri = documentSelectResult[0];
33              console.info('documentViewPicker.select to file succeed and uri is:' + uri);
34              if (event) {
35                event.result.handleFileList([uri]);
36              }
37            }).catch((err: BusinessError) => {
38              console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
39            })
40            return true;
41          })
42      }
43    }
44  }
45  ```
46
47
48- local.html页面代码。
49
50  ```html
51  <!DOCTYPE html>
52  <html>
53  <head>
54      <meta charset="utf-8">
55      <title>Document</title>
56  </head>
57
58  <body>
59  <!-- 点击上传文件按钮 -->
60  <input type="file" value="file"></br>
61  <meta name="viewport" content="width=device-width" />
62  </body>
63  </html>
64  ```
65