Put A File

Summary

An easy way to put a file to the cloud, for example the Personal Web Sharing built into OS X on Macintosh.

Introduction

Putting a disk file to a web server

The code

Non-blocking

You probably have some catch-all, long-lived class where the commands of your application are implemented. Add a member variables to its .h file:

NSURLConnection *http_;

and in the corresponding .m file, add the code to support this to your -(void)dealloc method:

-(void)dealloc {
...
  [http_ cancel];
  [http_ release];
  http_ = nil;
...
  [super dealloc];
}

You'll not use @property and @synthesize, but explicitly write the setter:

- (void)setHTTP:(NSURLConnection *)http {
  if (http_ != http) {
    [http_ cancel];
    [http_ release];
    http_ = [http retain];
  }
}

Now the code to start a file moving from your box is:

- (IBAction)fetchFile:(id)sender {
...
NSString *path = MyFunctionToReturnPath();
NSData *myData = [NSData dataWithContentsOfFile:path];
NSURL *url = [NSURL URLWithString:@"http://localhost/cgi-bin/catcher?Your+Title+Here"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request addValue:@"My Program/1.0.0" forHTTPHeaderField:@"User-Agent"];
[request addValue:@"no-cache" forHTTPHeaderField:@"Cache-Control"];
[request setHTTPBody:myData];
NSURLConnection *connection = 
  [NSURLConnection connectionWithRequest:request delegate:self];
[self setHTTP:connection];
} // we just return back to the main event loop

That sets the file moving to you. You'll need code to actually catch the file your "self" object above must implement some delegate mehtods that will be called back by the connection:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
  if (httpData_) {
    httpData_ appendData:data];
  } else {
    httpData_ = [data mutableCopy];
  }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// at this point httpData holds the entire file. You can save it to disk.
  [httpData_ release];
  http_ = nil;
}

- (void)connection:(NSURLConnection *)connection 
  didFailWithError:(NSError *)error {
  [httpData_ release];
  http_ = nil;
}

See Also

Further Work

A real program might provide manage multiple simultaneous connections, with an array of connections currently open, and a queue of pending connections.

Conclusion

This page has presented OS X Cocoa code for pushing a disk file to the web.