我在使用的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];
我有一个在nginx下运行的PHP服务器(使用Laravel)来处理此上传。我已经用Postman进行了测试,并且可以接受上传(期望文件名为“文件”)。
当我运行上面的objc代码时,服务器告诉我没有文件上传($_FILES
数组为空)。
我尝试了是否设置“ fileName”标头,并且尝试将“ Content-Type”设置为“ multipart / form-data”,但是这些都不起作用。
我如何才能NSURLSessionUploadTask
正确地将这些文件(从NSURL
)上传到服务器?
这篇文章似乎详细说明了类似的问题:NSURLSessionUploadTask没有将文件传递给php脚本
使用NSURLSessionUploadTask [uploadTaskWithRequest:fromFile:]时,文件以二进制形式在请求正文中发送。
要将文件保存在PHP中,您只需获取请求正文并将其保存到文件中即可。
显然,最好进行某种文件格式验证。
Objective-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
希望对您有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句