GTF*_*GTF 1 php file-upload objective-c nsurlsession nsurlsessionuploadtask
我在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];
Run Code Online (Sandbox Code Playgroud)
我有一个在nginx下运行的PHP服务器(使用Laravel)来处理这个上传.我已经使用Postman对其进行了测试,并且它接受了很好的上传(期待名为"file"的文件).
当我运行上面的objc代码时,服务器告诉我没有上传文件($_FILES数组为空).
我已尝试使用和不设置"fileName"标头,我尝试将"Content-Type"设置为"multipart/form-data",但这些都不起作用.
如何NSURLSessionUploadTask正确上传这些文件(从a 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];
Run Code Online (Sandbox Code Playgroud)
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
}
?>
Run Code Online (Sandbox Code Playgroud)
我写了一个代码示例,记录音频并将其上传到服务器:https: //github.com/gingofthesouth/Audio-Recording-Playback-and-Upload
我希望有所帮助.
| 归档时间: |
|
| 查看次数: |
4841 次 |
| 最近记录: |