使用NSURLSessionUploadTask将文件上传到PHP服务器 [英] Uploading file using NSURLSessionUploadTask to PHP server

查看:215
本文介绍了使用NSURLSessionUploadTask将文件上传到PHP服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在iOS应用程序中使用 NSURLSessionUploadTask 来创建视频上传系统。视频文件被保存到 NSURL ,所以我在我的上传方法中使用了下面的代码:

  request.HTTPMethod = @POST; 
[request addValue:@fileforHTTPHeaderField:@fileName];

//创建上传任务
NSURLSessionUploadTask * task = [session uploadTaskWithRequest:request fromFile:filePath completionHandler:^(NSData * data,NSURLResponse * response,NSError * error){
if(!error){
//处理成功
} else {
//处理错误
}
}];

//运行任务
[任务恢复];

我有一个在nginx下运行的PHP服务器(使用Laravel)来处理这个上传。我已经用Postman测试了它,它接受上传正常(期望名为file的文件)。

当我运行上面的objc代码时,服务器告诉我没有上传文件( $ _ FILES 数组是空的)。



设置文件名标题,我已经尝试将Content-Type设置为multipart / form-data,但这些都不起作用。

我怎样才能获得 NSURLSessionUploadTask 正确地上传这些文件(从 NSURL )到服务器?



这篇文章似乎详细的类似的问题:NSURLSessionUploadTask不是传递文件到php脚本当使用NSURLSessionUploadTask [uploadTaskWithRequest:fromFile:]时,文件被发送到php脚本文件中

请求正文为二进制。



用PHP保存该文件您可以简单地获取请求主体并将其保存到文件中。

显然,最好做一些文件格式验证。



目标代码:

  //定义路径
NSURL * URL = [NSURL URLWithString:kDestinationURL];

//创建请求
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@POST];

//配置NSURL会话
NSURLSessionConfiguration * config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@com.upload];
config.HTTPMaximumConnectionsPerHost = 1;
NSURLSession * session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];

//定义上传任务
NSURLSessionUploadTask * uploadTask = [session uploadTaskWithRequest:request fromFile:audioRecorder.url];

//运行它!
[uploadTask resume];

PHP代码

 <?php 
//保存文件的文件路径
$ file ='uploads / recording.m4v';

//获取请求正文
$ request_body = @file_get_contents('php:// input');

//获取关于文件的一些信息
$ file_info = new finfo(FILEINFO_MIME);

//提取mime类型
$ mime_type = $ file_info-> buffer($ request_body);

//逻辑处理返回的类型
switch($ mime_type)
{
casevideo / mp4; charset = binary:

//将请求主体写入文件
file_put_contents($ file,$ request_body);

break;

默认值:
//在这里处理错误的文件类型
}
?>

我写了一个录制音频并上传到服务器的代码示例:
<一个href =https://github.com/gingofthesouth/Audio-Recording-Playback-and-Upload =noreferrer> https://github.com/gingofthesouth/Audio-Recording-Playback-and-Upload



我希望有帮助。

I have a video upload system in an iOS app using NSURLSessionUploadTask. The video file is saved to an NSURL so I am using the following code in my upload method:

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];

I have a PHP server (using Laravel) running under nginx to handle this upload. I have tested it with Postman, and it accepts uploads fine (expecting a file under the name "file").

When I run the above objc code, the server tells me that no file has been uploaded (the $_FILES array is empty).

I have tried with and without setting the "fileName" header, and I've tried setting "Content-Type" to "multipart/form-data" but none of these works.

How can I get NSURLSessionUploadTask to properly upload these files (from an NSURL) to the server?

This post seems to detail a similar problem: NSURLSessionUploadTask not passing file to php script

解决方案

When using NSURLSessionUploadTask [uploadTaskWithRequest: fromFile:], the file is sent in the request body as binary.

To save that file in PHP you can simply get the request body and save it to file.

Obviously, it is best to do some sort of file format validation.

Objective-C Code:

// 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 Code:

<?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
    }
?>

I wrote a code example of recording audio and uploading it to a server here: https://github.com/gingofthesouth/Audio-Recording-Playback-and-Upload

I hope that helps.

这篇关于使用NSURLSessionUploadTask将文件上传到PHP服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆