iphone向Web服务器发送图片

 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}";
}
?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值