2013-07-11 74 views
1

我想上傳一個圖像到web服務,但是當我上傳它時,只有圖像的名稱是保存,但不是圖像。圖像不上傳到webservice

請找到供您參考的代碼和圖片。

- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 
{ 
    [self dismissModalViewControllerAnimated:YES]; 

    NSData *image = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage], 0.1); 

    NSMutableString *urlString = [[NSMutableString alloc] initWithFormat:@"name=thefile&&filename=recording"]; 
    [urlString appendFormat:@"%@", image]; 
    NSData *postData = [urlString dataUsingEncoding:NSASCIIStringEncoding 
           allowLossyConversion:YES]; 
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; 
    NSString *baseurl = @"http://192.168.2.34/Service1.svc/upload/filename.png"; 

    NSURL *url = [NSURL URLWithString:baseurl]; 
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; 
    [urlRequest setHTTPMethod: @"POST"]; 
    [urlRequest setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
    [urlRequest setValue:@"application/x-www-form-urlencoded" 
     forHTTPHeaderField:@"Content-Type"]; 
    [urlRequest setHTTPBody:postData]; 

    NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self]; 
    [connection start]; 

    NSLog(@"Started!"); 

} 

上傳圖像的圖像和名稱後顯示如下:

enter image description here

但是當我打開的圖像顯示爲零。

enter image description here

我不知道是怎麼回事wrong..kindly幫助我。

在此先感謝。

回答

1

這些線是錯誤的:

NSData *image = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage], 0.1); 
NSMutableString *urlString = [[NSMutableString alloc] initWithFormat:@"name=thefile&&filename=recording"]; 
[urlString appendFormat:@"%@", image]; 
NSData *postData = [urlString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
... 
[urlRequest setValue:@"application/x-www-form-urlencoded" 
    forHTTPHeaderField:@"Content-Type"]; 
[urlRequest setHTTPBody:postData]; 

替換:

NSData *image = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage], 0.1); 
... 
[urlRequest setHTTPBody:image]; 

而且你或許應該改變0.1到0.8什麼的,否則質量將是可怕的。

您還需要確保服務器正確讀取數據。這取決於你所使用的服務器端...在PHP中,這是你怎麼做:

$data = file_get_contents('php://input'); 
file_put_contents($data, 'filename.jpg'); 
+0

很好的答案...很好 – makumar

+0

真棒...它是工作文件..感謝 –

+0

如何在此代碼中上傳視頻 –

0

的問題是:

[urlString appendFormat:@"%@", image]; 

要鏈接的NSData對象在描述發佈數據,這是一個錯誤。 要上傳二進制文件,您需要序列化數據或使用多部分/表單數據POST請求。

這些是2個解決方案:

1)轉換圖像的NSData爲Base64與該類別(測試)

https://github.com/l4u/NSData-Base64

,然後做

[urlString appendFormat:@"&image=%@", [image base64EncodedString]]; 

你需要轉換在服務器上使用base64數據(在PHP中)

http://www.php.net/manual/en/function.base64-decode.php

2)實施 File Upload to HTTP server in iphone programming

我希望這有助於。