博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

iphone向Web服务器发送图片

Posted on 2011-07-21 18:35  BradyChen  阅读(1386)  评论(0编辑  收藏  举报
C代码  收藏代码
  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);  
C代码  收藏代码
  1. NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];  
C代码  收藏代码
  1. NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];  
  2.   
  3. result_btn.text = returnString;   

 

Php代码  收藏代码
  1. /Applications/XAMPP/htdocs  
  2.   
  3. imac:htdocs aitracy$ cat test-upload.php   
  4.   
  5. <?php  
  6. $uploaddir = './upload/';  
  7. echo "recive a image";  
  8. $file = basename($_FILES['userfile']['name']);  
  9. $uploadfile = $uploaddir . $file;  
  10.   
  11. if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {  
  12.     echo "/uploads/{$file}";  
  13. }  
  14. ?>