如何在Cocoa中使用WebView上传文件?

Dim*_*ian 7 upload cocoa file uploading webview

WebView有一个名为的方法

- (void)webView:(WebView *)sender runOpenPanelForFileButtonWithResultListener:(id < WebOpenPanelResultListener >)resultListener
Run Code Online (Sandbox Code Playgroud)

但是它上面几乎有0个文档和细节.在里面我显示一个打开的文件对话框并获取所选的文件名.

像这样

- (void)webView:(WebView *)sender runOpenPanelForFileButtonWithResultListener:(id < WebOpenPanelResultListener >)resultListener
{       
    NSOpenPanel* openDlg = [NSOpenPanel openPanel];

    [openDlg setCanChooseFiles:YES];

    [openDlg setCanChooseDirectories:NO];

    // process the files.
    if ( [openDlg runModal] == NSOKButton )
    {
        NSString* fileString = [[openDlg URL]absoluteString];
        [resultListener chooseFilename:fileString]; 
    }

}
Run Code Online (Sandbox Code Playgroud)

但是之后 ?

我该怎么办 ?在网站上,它显示我选择了一个文件,但是当您点击上传时,网站只返回错误,就像没有上传文件一样.我应该编写处理文件上传的代码还是什么?

我有点失落......

编辑:

事实上我让它工作....只需改变这里的代码:Cocoa webkit:如何在webkit中获取文件上传/文件系统访问权限,因为某些部分已被弃用

- (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]; 
        }
        [files release];
    }

}
Run Code Online (Sandbox Code Playgroud)

请享用 !

Dim*_*ian 8

我跟着Peter Hosey评论并且哇,我的代码现在很短,并且工作原理相同

- (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* files = [[openDlg URLs]valueForKey:@"relativePath"];
        [resultListener chooseFilenames:files];
    }

}
Run Code Online (Sandbox Code Playgroud)