1 //把图片转换为NSData
2 UIImage *image = [UIImage imageNamed:@"vim_go.png"];
3 NSData *imageData = UIImagePNGRepresentation(image);
4 // post url
5 NSString *urlString = @"http://10.28.4.162/test-upload.php";
6
7 // setting up the request object now
8 NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
9 [request setURL:[NSURL URLWithString:urlString]];
10 [request setHTTPMethod:@"POST"];
11 //
12 NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
13 NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
14 [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
15 //
16 NSMutableData *body = [NSMutableData data];
17 [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
18 [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"vim_go.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
19 [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
20 [body appendData:[NSData dataWithData:imageData]];
21 [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
22 [request setHTTPBody:body];
23
24 NSLog(@"%@",body);
25 NSLog(@"%@",request);
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
result_btn.text = returnString;
php代码:
/Applications/XAMPP/htdocs
imac:htdocs aitracy$ cat test-upload.php
<?php
$uploaddir = './upload/';
echo "recive a image";
$file = basename($_FILES['userfile']['name']);
$uploadfile = $uploaddir . $file;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "/uploads/{$file}";
}
?>