Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/244.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php NSURLSessionUploadTask未能上载文件_Php_Ios_File Upload_Nsurlconnection_Nsurlsession - Fatal编程技术网

Php NSURLSessionUploadTask未能上载文件

Php NSURLSessionUploadTask未能上载文件,php,ios,file-upload,nsurlconnection,nsurlsession,Php,Ios,File Upload,Nsurlconnection,Nsurlsession,下面是上载图像文件的片段。我只想使用NSURLSessionUploadTask,因为它提供了我想在我的应用程序中使用的后台上载功能 我还想在上传文件的同时发布参数 另外,我不擅长服务器端代码。谁能告诉我我做错了什么 上传代码 NSString* filePath = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"jpg"]; uint64_t bytesTotalForThisFi

下面是上载图像文件的片段。我只想使用NSURLSessionUploadTask,因为它提供了我想在我的应用程序中使用的后台上载功能

我还想在上传文件的同时发布参数

另外,我不擅长服务器端代码。谁能告诉我我做错了什么

上传代码

NSString* filePath = [[NSBundle mainBundle]
                      pathForResource:@"sample" ofType:@"jpg"];
uint64_t bytesTotalForThisFile = [[[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:NULL] fileSize];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:uploadPath];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%llu", bytesTotalForThisFile] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/octet-stream" forHTTPHeaderField:@"Content-Type"];

[request setTimeoutInterval:30];

NSString* filePath = [[NSBundle mainBundle]
                      pathForResource:@"sample" ofType:@"jpg"];


NSURLSessionUploadTask *taskUpload= [self.uploadSession uploadTaskWithRequest:request fromFile:[[NSURL alloc] initFileURLWithPath:filePath]];
<?php

$objFile = & $_FILES["file"];
$strPath = basename( $objFile["name"] );

if( move_uploaded_file( $objFile["tmp_name"], $strPath ) ) {
    print "The file " .  $strPath . " has been uploaded.";
} else {
    print "There was an error uploading the file, please try again!";
}
PHP代码

NSString* filePath = [[NSBundle mainBundle]
                      pathForResource:@"sample" ofType:@"jpg"];
uint64_t bytesTotalForThisFile = [[[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:NULL] fileSize];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:uploadPath];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%llu", bytesTotalForThisFile] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/octet-stream" forHTTPHeaderField:@"Content-Type"];

[request setTimeoutInterval:30];

NSString* filePath = [[NSBundle mainBundle]
                      pathForResource:@"sample" ofType:@"jpg"];


NSURLSessionUploadTask *taskUpload= [self.uploadSession uploadTaskWithRequest:request fromFile:[[NSURL alloc] initFileURLWithPath:filePath]];
<?php

$objFile = & $_FILES["file"];
$strPath = basename( $objFile["name"] );

if( move_uploaded_file( $objFile["tmp_name"], $strPath ) ) {
    print "The file " .  $strPath . " has been uploaded.";
} else {
    print "There was an error uploading the file, please try again!";
}

我将举一个代码示例。检查控制台上是否有任何错误

// 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
NSURL *url = <yourURL>;
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);
      }
}];
//1。配置
NSURLSessionConfiguration*配置=[NSURLSessionConfiguration defaultSessionConfiguration];
// 2. 如有必要,设置您的授权HTTP(示例api)
//[config setHTTPAdditionalHeaders:@{@'':}];
// 3. 最后,使用上述配置创建NSURLSession。
NSURLSession*session=[NSURLSession sessionWithConfiguration:config];
// 4. 设置您的请求URL
NSURL*url=;
NSMutableURLRequest*请求=[[NSMutableURLRequest alloc]initWithURL:url];
// 5. 设置您的HTTPMethod POST或PUT
[请求设置HttpMethod:@“放置”];
// 6. 封装文件(支持图像)
UIImage*image=[UIImage imageName:@“imageName”];
NSData*imageData=UIImageJPEG表示法(图像,1.0);
// 7. 您可以尝试使用UploadTaskWithRequestfromData
NSURLSessionUploadTask*taskUpload=[session uploadTaskWithRequest:request fromData:imageData completionHandler:^(NSData*数据,NSURLRResponse*响应,NSError*错误){
NSHTTPURLResponse*httpResp=(NSHTTPURLResponse*)响应;
如果(!error&&httpResp.statusCode==200){
//上传
}否则{
//保存/更新便笺时出错的警报
NSLog(@“ERROR:%@和HTTPREST ERROR:%ld”,ERROR,(long)httpResp.statusCode);
}
}];

如果这是完整的代码,那么您实际上并没有开始上传。NSURLSession任务不会自动启动(与某些NSURLConnection调用不同)。你必须显式地调用他们的resume方法来开始上传,否则任务将只是坐在那里什么也不做

其次,您应该真正使用URLForResource,而不是使用路径然后将其转换为URL。这不应该破坏你的代码,但它是一个干净得多,只使用URL开始

第三,如果您确实需要使用路径,方便方法(fileURLWithPath:)是您的朋友

第四,您不需要设置内容长度,IIRC,您可能不应该,因为如果NSURLSession协商任何类型的编码(例如压缩文件数据),您不知道内容长度实际上是多少

第五,如果文件很大,30秒可能不够长

第六,如果您运行的是较新版本的iOS或OS X,请确保您使用的是正确配置的HTTPS服务器,或者您添加了适当的应用程序传输安全异常


最后,如果您希望包括其他POST参数,而不仅仅是提供blob数据作为请求主体,那么您必须使用流式请求。当然,您可以简单地使用GET参数,我建议您这样做,因为这是一种非常简单的方法。:-)

我使用的后台会话不是默认的,也不允许在后台会话中使用完成处理程序。另外,NSData as image也不允许作为image。