0%

Cocoa中WebView允许选择本地上传文件

Cocoa中WebView允许选择本地上传文件

Cocoa中使用 webview 加载URL显示网页,在进行选择文件上传时候

1
2
<input type="file" name="uploadfile">

在webview上不能正常的弹出选择器,cef正常。

WebUIDelegate

解决该问题只需要实现 WebUIDelegate 的代理方法

1
2
- (void)webView:(WebView *)sender runOpenPanelForFileButtonWithResultListener:(id<WebOpenPanelResultListener>)resultListener;

实现内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#pragma mark -  webview
/// <input type="file">
- (void)webView:(WebView *)sender runOpenPanelForFileButtonWithResultListener:(id<WebOpenPanelResultListener>)resultListener {
// Create the File Open Dialog class.
NSOpenPanel* openDlg = [NSOpenPanel openPanel];

// Enable the selection of files in the dialog.
[openDlg setCanChooseFiles:YES];

// Enable the selection of directories in the dialog.
[openDlg setCanChooseDirectories:NO];

if ([openDlg runModal] == NSOKButton)
{
NSArray* URLs = [openDlg URLs];
NSMutableArray *files = [[NSMutableArray alloc]init];
for (int i = 0; i <[URLs count]; i++) {
NSString *filename = [[URLs objectAtIndex:i]relativePath];
[files addObject:filename];
}

for(int i = 0; i < [files count]; i++)
{
NSString* fileName = [files objectAtIndex:i];
[resultListener chooseFilename:fileName];
}
}
}

参考