2015-02-17 27 views
2

下面我有此代碼發送的圖片和一些文字到我的服務器:NSURLSessionUploadTask不上傳圖片與參數

NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration]; 

    self.session = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate:self delegateQueue: nil]; 

    NSString *requestURL = @"http://www.website.com.br/receive.php?name=StackOverflow"; 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestURL]]; 

    [request setHTTPMethod:@"POST"]; 

    UIImage *imagem = [UIImage imageNamed:@"Image.jpg"]; 

    NSData *imageData = UIImageJPEGRepresentation(imagem, 1.0); 

    self.uploadTask = [self.session uploadTaskWithRequest:request fromData:imageData]; 

    [self.uploadTask resume]; 


-(void)URLSession:(NSURLSession *)session 
     dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{ 

    NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
    NSLog(@"%@",newStr); 
} 

PHP

<?php 
echo $_POST['name']; 
?> 

這段代碼的問題是

012:該 didReceiveData方法不接收數據,傳送至服務器,它只有當我在PHP文件把這段代碼得到一個

然而它返回一個空數組,爲什麼發生這種情況?

解決

嗯,我解決我的問題,讓我們去,在.h文件中,你需要實現這個協議和一個屬性:

< NSURLSessionDelegate, NSURLSessionTaskDelegate> 
@property (nonatomic) NSURLSessionUploadTask *uploadTask; 

而在.m文件有一個IBAction類型的方法並且它連接到我們認爲存在的特定按鈕,我們只需要這樣做:

- (IBAction)start:(id)sender { 

    if (self.uploadTask) { 
     NSLog(@"Wait for this process finish!"); 
     return; 
    } 

    NSString *imagepath = [[self applicationDocumentsDirectory].path stringByAppendingPathComponent:@"myImage.jpg"]; 
    NSURL *outputFileURL = [NSURL fileURLWithPath:imagepath]; 


    // Define the Paths 
    NSURL *icyURL = [NSURL URLWithString:@"http://www.website.com/upload.php"]; 

    // Create the Request 
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:icyURL]; 
    [request setHTTPMethod:@"POST"]; 

    // Configure the NSURL Session 
    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.sometihng.upload"]; 

    NSURLSession *upLoadSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil]; 

    // Define the Upload task 
    self.uploadTask = [upLoadSession uploadTaskWithRequest:request fromFile:outputFileURL]; 

    // Run it! 
    [self.uploadTask resume]; 

} 

並實現一些委託方法:

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend { 

    NSLog(@"didSendBodyData: %lld, totalBytesSent: %lld, totalBytesExpectedToSend: %lld", bytesSent, totalBytesSent, totalBytesExpectedToSend); 

} 

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { 
    if (error == nil) { 
     NSLog(@"Task: %@ upload complete", task); 
    } else { 
     NSLog(@"Task: %@ upload with error: %@", task, [error localizedDescription]); 
    } 
} 

而對於結果,你需要創建一個PHP文件與此代碼:

<?php 

$fp = fopen("myImage.jpg", "a");//If image come is .png put myImage.png, is the file come is .mp4 put myImage.mp4, if .pdf myImage.pdf, if .json myImage.json ... 

$run = fwrite($fp, file_get_contents("php://input")); 

fclose($fp); 

?> 

回答

0

您應該將NSData轉換成像NSArray一個更易於管理的格式。要做到這一點,你必須嘗試類似:

NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data] 
+0

我的代碼中有兩個NSDatas,一個用於發送數據,另一個用於接收,我怎麼把你的代碼放在兩個中? – LettersBa 2015-02-18 02:09:06

+0

我的方法didReceiveData用於:取消歸檔數據和我收到一個錯誤崩潰:難以理解的存檔(0×41,0x72,0x72,0x61,0x79的,是0xA,0×28,是0xA)」 – LettersBa 2015-02-18 02:10:51

+0

我解決我的問題,謝謝... – LettersBa 2015-02-18 14:19:51

2

將圖像上傳到Dropbox的代碼示例。

// 1. config 
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; 

// 2. if necessary set your Authorization HTTP (example api) 
// [config setHTTPAdditionalHeaders:@{@"<setYourKey>":<value>}]; 

// 3. Finally, you create the NSURLSession using the above configuration. 
NSURLSession *session = [NSURLSession sessionWithConfiguration:config]; 

// 4. Set your Request URL (example using dropbox api) 
NSURL *url = [Dropbox uploadURLForPath:<yourFullPath>];; 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; 

// 5. Set your HTTPMethod POST or PUT 
[request setHTTPMethod:@"PUT"]; 

// 6. Encapsulate your file (supposse an image) 
UIImage *image = [UIImage imageNamed:@"imageName"]; 
NSData *imageData = UIImageJPEGRepresentation(image, 1.0); 

// 7. You could try use uploadTaskWithRequest fromData 
NSURLSessionUploadTask *taskUpload = [session uploadTaskWithRequest:request fromData:imageData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 

    NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response; 
    if (!error && httpResp.statusCode == 200) { 

     // Uploaded 

    } else { 

     // alert for error saving/updating note 
     NSLog(@"ERROR: %@ AND HTTPREST ERROR : %ld", error, (long)httpResp.statusCode); 
     } 
}]; 

- (NSURL*)uploadURLForPath:(NSString*)path 
{ 
    NSString *urlWithParams = [NSString stringWithFormat:@"https://api-content.dropbox.com/1/files_put/sandbox/%@/%@", 
           appFolder, 
           [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];  
    NSURL *url = [NSURL URLWithString:urlWithParams]; 
    return url; 
} 
+0

我們如何通過文件傳遞參數? – gypsicoder 2015-10-19 07:07:38

+0

@gypsicoder你可以使用'[配置setHTTPAdditionalHeaders:@ {@ 「授權」:Dropbox的apiAuthorizationHeader]}]'例如Dropbox的,以授權添加到頭部 - 在這裏看到更多的細節[鏈接](https://開頭WWW。 dropbox.com/developers-v1/core/docs#oa2-authorize) - api – 2015-10-21 01:58:28