首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSURLSessionUploadTask不上传带有参数的图像

NSURLSessionUploadTask不上传带有参数的图像
EN

Stack Overflow用户
提问于 2015-02-17 20:30:51
回答 2查看 2.6K关注 0票数 2

下面的代码向我的服务器发送了一个图像和一些文本:

代码语言:javascript
复制
 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);
}

代码语言:javascript
复制
<?php
echo $_POST['name'];
?>

此代码的问题在于,didReceiveData方法没有接收到服务器的数据,只有当我将该代码放入php文件中时,它才会得到一个NSData

代码语言:javascript
复制
print_r($_FILES);

然而,它返回一个空数组,为什么会发生这种情况?

解决了

好吧,我解决了我的问题,让我们开始吧,在.h文件中,您需要实现这个协议和一个属性:

代码语言:javascript
复制
< NSURLSessionDelegate, NSURLSessionTaskDelegate>
@property (nonatomic) NSURLSessionUploadTask *uploadTask;

虽然在.m文件中有一个IBAction类型的方法,并且它连接到我们认为存在的一个特定按钮,但是我们只需要这样做:

代码语言:javascript
复制
- (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];

}

并执行一些委托方法:

代码语言:javascript
复制
- (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文件:

代码语言:javascript
复制
<?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);

?>
EN

回答 2

Stack Overflow用户

发布于 2015-07-07 18:47:23

将图像上传到dropbox的代码示例。

代码语言:javascript
复制
// 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;
}
票数 2
EN

Stack Overflow用户

发布于 2015-02-17 21:40:49

您应该将NSData转换为更易于管理的格式,如NSArray。要做到这一点,您必须尝试如下:

代码语言:javascript
复制
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data] 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28570574

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档