如何从文件浏览器将文件保存到临时目录

时间:2014-09-24 13:31:25

标签: objective-c xcode cocoa nsurl temporary-files

我正在使用此方法打开文件浏览器并仅搜索图像文件。

NSOpenPanel* openPanel = [NSOpenPanel openPanel];
NSArray* imageTypes = [NSImage imageTypes];
[openPanel setCanChooseFiles:YES];
[openPanel setCanChooseDirectories:NO];
[openPanel setAllowsMultipleSelection:NO];
[openPanel setResolvesAliases:YES];
[openPanel setAllowedFileTypes:imageTypes];
[openPanel setPrompt:@"Upload"];
[openPanel setDirectoryURL:[NSURL fileURLWithPath:NSHomeDirectory()]];
[openPanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
    [openPanel close];

单击“上传”按钮时,对话框将关闭。如何将打开的图像保存到特定名称下的临时目录? 感谢

1 个答案:

答案 0 :(得分:0)

NSOpenPanel类不进行任何类型的文件处理。为了获取用户选择的文件,您可以使用其URLs方法,然后使用NSTemporaryDirectory()将该URL上的文件复制到目标。这是(未经测试的)代码的示例:

NSOpenPanel* openPanel = [NSOpenPanel openPanel];
NSArray* imageTypes = [NSImage imageTypes];
[openPanel setCanChooseFiles:YES];
[openPanel setCanChooseDirectories:NO];
[openPanel setAllowsMultipleSelection:NO];
[openPanel setResolvesAliases:YES];
[openPanel setAllowedFileTypes:imageTypes];
[openPanel setPrompt:@"Upload"];
[openPanel setDirectoryURL:[NSURL fileURLWithPath:NSHomeDirectory()]];
[openPanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
   if (result != NSOKButton) {
       return;
   }

   NSString *myString = [[[openPanel URLs] objectAtIndex:0] absoluteString];
   NSError *error = nil;
   [[NSFileManager defaultManager] copyItemAtPath:myString toPath:NSTemporaryDirectory() error:&error];
   if(error) {
       // Error! Tell the user by showing an NSAlert, etc.
   } 
}];

这是相当简单的,如果你在网上搜索"如何使用Cocoa复制文件"那么你会发现过多的答案。同样如何访问NSOpenPanel返回的文件。