douyinyi7766 2014-09-30 14:37
浏览 162
已采纳

使用NSURLSessionUploadTask将文件上载到PHP服务器

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

  • 写回答

1条回答 默认 最新

  • douxiandiyo58855 2015-02-02 01:19
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计