下面是上传图像文件的片段。我只想使用NSURLSessionUploadTask,因为它提供了我想在应用程序中使用的后台上传功能。
此外,我想POST参数与文件上传。
此外,我不擅长服务器端代码。有人能告诉我我做错了什么吗。
上传代码
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代码
<?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!";
}
从服务器端,我得到$_FILES 的空数组
我将举一个代码示例。检查控制台上是否有任何错误。
// 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);
}
}];
如果这是完整的代码,那么您实际上并没有开始上传NSURLSession任务不会自动启动(与某些NSURLConnection调用不同)。你必须明确地调用他们的简历方法来开始上传,否则任务就会无所事事。
其次,您应该真正使用URLForResource,而不是使用路径然后将其转换为URL。这不应该破坏你的代码,但一开始只使用URL会干净得多。
第三,如果你真的需要使用路径,方便的方法(fileURLWithPath:)是你的朋友。
第四,您不需要设置内容长度和IIRC,您可能不应该设置,因为如果NSURLSession协商任何类型的编码(例如压缩文件数据),您不知道内容长度实际是多少。
第五,如果文件很大,30秒可能不够长。
第六,如果您在较新版本的iOS或OS X上运行,请确保您使用了正确配置的HTTPS服务器,或者添加了适当的应用程序传输安全例外。
最后,如果您希望包含其他POST参数,而不是仅提供数据块作为请求主体,则必须使用流式请求。当然,您可以简单地使用GET参数,我建议您这样做,因为这是一种非常简单的方法。:-)