简体   繁体   中英

How do I save file to temp directory from file browser

I am using this method to open the file browser and search for an image file only.

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];

When the 'Upload' button is clicked, the dialog box closes. How can I save the opened image to the temporary directory under a specific name? Thanks

The NSOpenPanel class does not do any sort of file handling. In order to get the file that you user selected, you can use its URLs method, and then copy the file at that URL to the destination using NSTemporaryDirectory() . Here's an example of (un-tested) code:

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.
   } 
}];

This is fairly straightforward and if you had searched on the net for "how to copy a file using Cocoa" then you would have found a plethora of answers. Same for how to access the files returned by NSOpenPanel .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM