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);  

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. ?>  


 







分享给朋友:
您可能感兴趣的文章:
随机阅读: