我有一个视频上传系统在一个iOS应用程序使用NSURLSessionUploadTask。视频文件被保存到一个NSURL中,所以我在上传方法中使用了以下代码:
request.HTTPMethod = @"POST";
[request addValue:@"file" forHTTPHeaderField:@"fileName"];
// Create upload task
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromFile:filePath completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(!error) {
// handle success
} else {
// handle error
}
}];
// Run the task
[task resume];我有一个PHP服务器(使用Laravel)在nginx下运行来处理这个上传。我已经用Postman测试过它,它接受上传很好(期待一个名为“file”的文件)。
当我运行上述objc代码时,服务器告诉我没有上传任何文件( $_FILES数组为空)。
我尝试过使用和不设置"fileName“标题,并且尝试将”Content“设置为"multipart/form-data”,但这些都没有效果。
如何让NSURLSessionUploadTask正确地将这些文件(从NSURL)上传到服务器?
这篇文章似乎详细描述了一个类似的问题:NSURLSessionUploadTask not passing file to php script
发布于 2015-02-02 01:19:48
当使用NSURLSessionUploadTask uploadTaskWithRequest: fromFile:时,文件以二进制形式在请求体中发送。
要将该文件保存在PHP中,只需获取请求体并将其保存到文件中即可。
显然,最好进行某种类型的文件格式验证。
目标-C代码:
// Define the Paths
NSURL *URL = [NSURL URLWithString:kDestinationURL];
// Create the Request
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];
// Configure the NSURL Session
NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.upload"];
config.HTTPMaximumConnectionsPerHost = 1;
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
// Define the Upload task
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromFile:audioRecorder.url];
// Run it!
[uploadTask resume];PHP代码:
<?php
// File Path to save file
$file = 'uploads/recording.m4v';
// Get the Request body
$request_body = @file_get_contents('php://input');
// Get some information on the file
$file_info = new finfo(FILEINFO_MIME);
// Extract the mime type
$mime_type = $file_info->buffer($request_body);
// Logic to deal with the type returned
switch($mime_type)
{
case "video/mp4; charset=binary":
// Write the request body to file
file_put_contents($file, $request_body);
break;
default:
// Handle wrong file type here
}
?>我编写了一个记录音频并将其上传到服务器的代码示例:https://github.com/gingofthesouth/Audio-Recording-Playback-and-Upload
我希望这能帮上忙。
https://stackoverflow.com/questions/26123524
复制相似问题