2013-12-19 85 views
0

我正嘗試將圖像從我的應用上傳到我的服務器。我正在學習本教程(http://zcentric.com/2008/08/29/post-a-uiimage-to-the-web/)。當我複製教程中的代碼時,我得到一堆警告和錯誤,所以我修改了它,如下所示。將圖像上傳到服務器時出現故障

正在調用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阿東在Web瀏覽器作爲thub規則 – amar

+0

阿馬爾嗨的服務,將是這樣的服務器上的設置? – user2492064

+0

其每個plce的「\ r \ n - %@ \ r \ n」試試這個 – 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沒有被維護,並且不應該被012開發人員稱爲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

當你在圖像追加到身體的內容處置應該是一個附件沒有表單數據,要附加身體上的圖像數據之前。所以將以下代碼:

[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]]; 
相關問題