2013-03-21 152 views
2

我使用IOS这些代码上传我的形象如何上传图像到服务器

它几乎与上Internet

NSData *uploadImage = UIImageJPEGRepresentation(self.image, 1) ; 
NSString *uploadURL = @"http://...../jeff.php" ; 

NSMutableURLRequest *uploadRequest = [[NSMutableURLRequest alloc] init]; 
[uploadRequest setURL:[NSURL URLWithString:uploadURL]] ; 
[uploadRequest setHTTPMethod:@"POST"] ; 

NSString *boundary = @"---------------------------14737809831466499882746641449"; 
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data;boundary=%@",boundary]; 
[uploadRequest addValue:contentType forHTTPHeaderField: @"Content-Type"]; 

NSMutableData *body = [NSMutableData data]; 
[body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:[@"Content-Disposition:form-data; name=\"userfile\"; filename=\"test.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:[@"Content-Type: application/octet-streamrnrn\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:[NSData dataWithData:uploadImage]]; 
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 

[uploadRequest setHTTPBody:body]; 

NSData *returnData = [NSURLConnection sendSynchronousRequest:uploadRequest returningResponse:nil error:nil]; 
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; 
NSLog(@"echo:%@",returnString); 

另一个代码相同的我的PHP是

$uploaddir = './uploads/'; 
$file = basename($_FILES['userfile']['name']); 
$uploadfile = $uploaddir . $file; 

if (is_uploaded_file($_FILES['userfile']['tmp_name'])) 
{ 
    echo "yes \r\n"; 
} 
else 
{ 
    echo "NO \r\n"; 
} 

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) 
{ 
    echo "http://...../uploads/{$file}"; 
} 

但它不起作用

我的上传文件夹是/ var/www/uploads

+1

的委托方法?定义'不工作' – Raptor 2013-03-21 10:00:40

+0

我强烈建议用AFNetworking来做这件事http://stackoverflow.com/questions/10888167/afnetworking-uploading-image – jbat100 2013-03-21 13:40:45

回答

0

FOR POST METHOD READ MY OWN ANSWER FROM.

并使用此代码用于图片发布。

NSString *imgPath = fullPathOfYourImage; 
    if([[NSFileManager defaultManager] fileExistsAtPath:imgPath]) 
    { 
     [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];               
     [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"photo\"; filename=\"YourImageName.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
                               ^..YourImageName….^ 

     [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
     [body appendData:[NSData dataWithContentsOfFile:imgPath]]; 
     [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
    } 
+0

撰写多部分表格数据信息是相当容易出错的。您的答案在一些重要细节中不正确:您的边界不正确,图像数据应该具有相应的MIME类型 - application/octet-stream不适用。 – CouchDeveloper 2014-03-31 15:39:01

+0

如何将多个图像文件上传到服务器 – Ravindhiran 2014-05-29 07:33:49

0

你可以试试这个方法,我测试,并正在

的PHP

<?php 
$image = $_REQUEST['image']; 

$imageFileName = "miImage.jpg"; 

$binary = base64_decode($image); 
$file = fopen($imageFileName, 'wb'); 
fwrite($file, $binary); 
fclose($file); 
echo "Upload completed with success"; 
?> 

在YourViewController.h文件

@interface YourViewController : UIViewController { 
    NSURLConnection *serverConnection; 
    NSMutableData *returnData; 
} 

复制并粘贴此方法在YourViewController.m文件中

- (NSString*)base64forData:(NSData*) theData { 
    const uint8_t* input = (const uint8_t*)[theData bytes]; 
    NSInteger length = [theData length]; 

    static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/="; 

    NSMutableData* data = [NSMutableData dataWithLength:((length + 2)/3) * 4]; 
    uint8_t* output = (uint8_t*)data.mutableBytes; 

    NSInteger i; 
    for (i=0; i < length; i += 3) { 
     NSInteger value = 0; 
     NSInteger j; 
     for (j = i; j < (i + 3); j++) { 
      value <<= 8; 

      if (j < length) { 
       value |= (0xFF & input[j]); 
      } 
     } 

     NSInteger theIndex = (i/3) * 4; 
     output[theIndex + 0] =     table[(value >> 18) & 0x3F]; 
     output[theIndex + 1] =     table[(value >> 12) & 0x3F]; 
     output[theIndex + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '='; 
     output[theIndex + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '='; 
    } 

    return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; 
} 

现在,这是行代码发送图像

NSURL *sendURL = [NSURL URLWithString:@"http://yourdomain.com/yourphp.php"]; 

NSMutableURLRequest *sendRequest = [NSMutableURLRequest requestWithURL:sendURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30]; 

[sendRequest setHTTPMethod:@"POST"]; 

[sendRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 

NSData *imageData = UIImageJPEGRepresentation(yourImage, 1.0); 

NSString *encodedString = [[self base64forData:imageData] stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"]; 

stringBody = [[NSString alloc] initWithFormat:@"image=%@", encodedString]; 

[sendRequest setHTTPBody:[stringBody dataUsingEncoding:NSUTF8StringEncoding]]; 

serverConnection = [[NSURLConnection alloc] initWithRequest:sendRequest delegate:self]; 

[serverConnection start]; 

最后一件事是设置提示任何错误的服务器连接

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    returnData = [[NSMutableData alloc] init]; 
} 

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

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; 

    NSLog(@"Response: %@", responseString); 

    if ([responseString isEqualToString:@"Upload completed with success"]) { 

     /* Do something on success */ 

    } else { 

     /* Do something if not succeeded */ 

    } 
} 

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    /* Do something in fail */ 
} 
相关问题