NSURLSessionUploadTask 不上传带参数的图片

Posted

技术标签:

【中文标题】NSURLSessionUploadTask 不上传带参数的图片【英文标题】:NSURLSessionUploadTask don't upload image with parameters 【发布时间】:2015-02-17 20:30:51 【问题描述】:

我有以下代码,它将图像和一些文本发送到我的服务器:

 NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];

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

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

    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'];
?>

这段代码的问题是didReceiveData方法没有接收到去服务器的数据,当我把这段代码放在php文件中时它只得到一个NSData

print_r($_FILES);

然而它返回一个空数组,为什么会这样?

已解决

好吧,我解决了我的问题,让我们开始吧,在 .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);

?>

【问题讨论】:

【参考方案1】:

上传图片到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;

【讨论】:

我们如何通过文件传递参数? @gypsicoder 例如,您可以使用[config setHTTPAdditionalHeaders:@@"Authorization": [Dropbox apiAuthorizationHeader]]; 将保管箱授权添加到标头 - 在此处查看更多详细信息link - api【参考方案2】:

您应该将NSData 转换为更易于管理的格式,例如NSArray。为此,您必须尝试以下操作:

NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data] 

【讨论】:

我的代码中有两个 NSData,一个用于发送数据,另一个用于接收,我如何将您的代码放在两者中? 我在方法 didReceiveData: 中使用了取消归档数据并收到崩溃错误:无法理解的归档 (0x41, 0x72, 0x72, 0x61, 0x79, 0xa, 0x28, 0xa)' 好的,抱歉我今天不在电脑旁。您可以将您的解决方案添加为您自己问题的答案,而不是更新您的问题;如果其他答案也有帮助,请点赞。

以上是关于NSURLSessionUploadTask 不上传带参数的图片的主要内容,如果未能解决你的问题,请参考以下文章

NSURLSessionUploadTask 不上传带参数的图片

NSURLSessionUploadTask 获取响应数据

NSURLSessionUploadTask 在创建后直接取消[重复]

当应用程序挂起时,我如何知道 NSURLSessionUploadTask 是不是正在工作?

iOS开发之网络编程--5NSURLSessionUploadTask+NSURLSessionDataDelegate代理上传

我可以使用 NSURLSessionUploadTask 进行离线同步任务吗?