2011/07/19

透過NSURLConnection和NSMutableURLRequest上傳/POST一個檔案

直接來看code
NSURLConnection *conn;
NSMutableData *tempData;  /* Store response */

- (void)uploadFile {
    NSString *boundary = @"0xKhTmLbOuNdArY";
    NSData *imgData = UIImageJPEGRepresentation(image.image, 90);  /* Image data come from UIImageView */
    NSString *urlString = @"http://my_server/upload.php";
    NSURL *url = [[NSURL alloc]initWithString:urlString];

    /* Set up request */
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];

    /* Prepare content part */
    NSMutableData *postData = [NSMutableData dataWithCapacity:[imgData length] + 512];
    [postData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"file.bin\"\r\n\r\n", @"image"] dataUsingEncoding:NSUTF8StringEncoding]];
    [postData appendData:imgData];
    [postData appendData: [[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    /* Assign content part */
    [urlRequest setHTTPBody:postData];

    tempData = [NSMutableData alloc];
    conn = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
}


Prepare 4 delegate
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [conn release];
    NSLog(@"Error occur");
}

- (void)connection: (NSURLConnection *)connection didReceiveResponse: (NSURLResponse *)aResponse {
    NSInteger status = (NSInteger)[(NSHTTPURLResponse *)aResponse statusCode];
    NSLog(@"%d", status);
}

-(void) connection:(NSURLConnection *)connection didReceiveData: (NSData *) incomingData {
 [tempData appendData:incomingData];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString *loadData = [[NSMutableString alloc] initWithData:tempData encoding:NSUTF8StringEncoding];    
    NSLog(@"%@", loadData);
}


Server - PHP sample code
<?php 
    if (isset($_FILES["image"]))
    {
        print_r($_FILES["image"]);
    }
?>

參考資料
CocoaDev: HTTPFileUploadSample


沒有留言:

張貼留言