• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - NSURLSessionUploadTask 不上传带参数的图片

[复制链接]
菜鸟教程小白 发表于 2022-12-12 14:19:50 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

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

 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"OST"];

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

    NSData *imageData = UIImageJPEGRepresentation(imagem, 1.0);

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

    [self.uploadTask resume];


-(void)URLSessionNSURLSession *)session
         dataTaskNSURLSessionDataTask *)dataTask didReceiveDataNSData *)data{

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

PHP

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

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

print_r($_FILES);

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

已解决

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

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

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

- (IBAction)startid)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"OST"];

    // 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 fromFileutputFileURL];

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

}

并实现一些委托(delegate)方法:

- (void)URLSessionNSURLSession *)session taskNSURLSessionTask *)task didSendBodyDataint64_t)bytesSent totalBytesSentint64_t)totalBytesSent totalBytesExpectedToSendint64_t)totalBytesExpectedToSend {

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

}

- (void)URLSessionNSURLSession *)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);

?>



Best Answer-推荐答案


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

// 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;
}

关于ios - NSURLSessionUploadTask 不上传带参数的图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28570574/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap