2013-12-19 4 views
0

Я пытаюсь загрузить изображение из своего приложения на свой сервер. Я следую этому руководству (http://zcentric.com/2008/08/29/post-a-uiimage-to-the-web/). Когда я копирую код из учебника, я получаю кучу предупреждений и ошибок, поэтому я изменил его, как показано ниже.Trouble Загрузка изображения на сервер

Вызывается метод uploadImage, а twitterImage содержит нужную фотографию, но изображение не загружается в каталог user_photos. Любые рекомендации были бы замечательными!

Вот мое приложение код:

-(void)uploadImage { 

NSData *imageData = UIImageJPEGRepresentation(twitterImage, 90); 
NSString *urlString = @"http://website.com/user_photo_upload.php"; 

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

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

NSMutableData *body = [NSMutableData data]; 
[body appendData:[[NSString stringWithFormat:@"rn--%@rn",boundary] 
    dataUsingEncoding:NSUTF8StringEncoding]]; 

    [body appendData:[@"Content-Disposition: form-data;name=\"userfile\"; 
    filename=\"ipodfile.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 

[body appendData:[@"Content-Type: application/octet-streamrnrn" 
    dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:[NSData dataWithData:imageData]]; 
[body appendData:[[NSString stringWithFormat:@"rn--%@--rn",boundary] 
    dataUsingEncoding:NSUTF8StringEncoding]]; 
[request setHTTPBody:body]; 

NSData *returnData = [NSURLConnection sendSynchronousRequest:request 
    returningResponse:nil error:nil]; 
NSString *returnString = [[NSString alloc] initWithData:returnData 
    encoding:NSUTF8StringEncoding]; 
} 

Вот мой user_photo_upload.php файл:

<?php 

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

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

?> 
+0

Сначала проверьте обслуживание с помощью любого REST ADON на веб-браузер, как правило, thub – amar

+0

Привет Amar, это будет установка на сервере ? – user2492064

+0

его «\ r \ n -% @ \ r \ n» на каждом plce попробуйте это – amar

ответ

0

В моем предложении, вы можете использовать ASIHTTPRequest рамки для загрузки изображений к серверу. Вы можете загрузить фреймворк с here. Это легко понять.

Смотрите ниже код относительно загрузки изображений с использованием ASIHTTPRequest

NSData *imgData = UIImageJPEGRepresentation(IMAGE, 0.9); 
formReq = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlString]]; 
formReq.delegate = self; 
[formReq setPostValue:VAL1 forKey:KEY1]; 
if (imgData) { 
    [formReq setData:imgData withFileName:[NSString stringWithFormat:@"ipodfile.jpg"] andContentType:@"image/jpeg" forKey:@"userfile"]; 
} 
[formReq startSynchronous]; 

Вы также можете обратиться хороший учебник here

+0

должна прекратить действие asihttp в настоящее время не поддерживается – amar

0

Если вы хотите, чтобы перейти от NSMutableURLRequest, то лучше всего будет AFNetworking получить его from here

ASIHTTPRequest не поддерживается и не должен использоваться, как указано разработчиком из library here примера изображения загрузить

-(void)call 
    { 
     //the image name is Denise.jpg i have uses image you can youse any file 
     //just convert it to nsdat in an appropriateway 
     UIImage *image= [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Denise" ofType:@"jpg"]]; 
     // getting data from image 
     NSData *photoData= UIImagePNGRepresentation(image); 

     // making AFHttpClient 
     AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"your url string"]]; 

     //setting headers 
     [client setDefaultHeader:@"multipart/form-data; charset=utf-8; boundary=0xKhTmLbOuNdArY" value:@"Content-Type"]; 
     [client setDefaultHeader:@"key" value:@"value"]; 
     NSMutableURLRequest *request1 = [client multipartFormRequestWithMethod:@"POST" path:@"application/uploadfile" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) { 
     //setting body 

      [formData appendPartWithFormData:[[NSString stringWithFormat:@"Value"] dataUsingEncoding:NSUTF8StringEncoding] name:@"Key"]; 
      [formData appendPartWithFormData:[[NSString stringWithFormat:@"Value"] dataUsingEncoding:NSUTF8StringEncoding] name:@"Key"]; 
//... 
      [formData appendPartWithFileData:photoData name:@"file_data" fileName:@"file.png" mimeType:@"image/png"]; 
     }]; 
     [request1 setTimeoutInterval:180]; 
     AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request1]; 
     [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) { 
      NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite); 
      float progress = totalBytesWritten/(float)totalBytesExpectedToWrite; 
     // use this float value to set progress bar. 
     }]; 
     [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) 
     { 

      NSDictionary *jsons = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil]; 
      NSLog(@"%@",responseObject); 
      NSLog(@"response headers: %@", [[operation response] allHeaderFields]); 
      NSLog(@"response: %@",jsons); 

     } 
             failure:^(AFHTTPRequestOperation *operation, NSError *error) 
     { 

      if([operation.response statusCode] == 403) 
      { 
       NSLog(@"Upload Failed"); 
       return; 
      } 
      NSLog(@"error: %@", [error debugDescription]); 

     }]; 
     [operation start]; 
    } 
0

Когда Вы прилагая изображение для тела Content-Disposition должна быть вложением не форм-данные, просто прежде чем вы прилагая данные изображений на теле , поэтому замените следующий код:

[body appendData:[@"Content-Disposition: form-data;name=\"userfile\"; 
filename=\"ipodfile.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 

с этим:

[body appendData:[@"Content-Disposition: attachment;name=\"userfile\"; 
filename=\"ipodfile.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
Смежные вопросы