SURLSessionUploadTask不将文件传递给php脚

SURLSessionUploadTask不将文件传递给php脚

本文介绍了NSURLSessionUploadTask不将文件传递给php脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我只是将content-type标头设置为multipart/form-data,没有任何区别.我的原始问题如下:

Ok, I just set the content-type header to multipart/form-data with no difference. My original question is below:

这是我关于堆栈溢出的第一个问题,希望我做得对.

This is my first question on stack overflow, I hope I'm doing it right.

我只是学习Objective-C,最近完成了斯坦福课程的在线版本.我对PHP和HTML几乎一无所知.我正在使用的php脚本和html大多是从教程中复制的.Obj-C对我来说更有意义.

I am only learning Objective-C, having recently completed the online version of the Stanford course. I know virtually nothing about php and html. The php script and the html I am using are mostly copied off a tutorial. Obj-C makes more sense to me.

问题:

我有一个php脚本.它将上传图像文件.从服务器上同一文件夹中的html文件调用该文件时,它可以正常工作.当我从obj-c调用该脚本时,我试图使该脚本正常工作.似乎可以运行,它返回200,obj-c确实调用了php,但是在线文件夹中没有文件.

I have a php script. It uploads an image file. It works properly when called from an html file in the same folder on the server. I am trying to get the same script to work when it is called from my obj-c. It seems to run, it returns 200, the obj-c does call the php, but no file appears in the online folder.

由于它只是在ios7中引入的,因此在网络上似乎很少.我没有找到与文件上传有关的示例,它们都与下载有关,只是说上传是相似的.我所做的事情似乎可以满足我找到的所有教程.

There seems to be very little about this on the web since it was only introduced in ios7. No examples I have found deal with file upload, they all deal with download and merely say that upload is similar. What I have done seems to satisfy any tutorials I have found.

我所知道的是:

  • 当在服务器上的html文件中调用php时,php可以工作,并且文件已上传
  • obj-c肯定在调用php脚本(我在php中写了一些日志记录(使用file_put_contents),以确认运行obj-c时正在调用该脚本)
  • obj-c几乎可以肯定上传图像文件(如果我在obj-c中使用委托方法,则显示上传进度)
  • 但是php脚本未接收到文件(我写到php中的日志显示,从obj-c调用时,$ _ FILES没有任何值.从html调用时,它按预期工作)
  • 我刚刚编辑了php以记录它接收到的标头,并且它确实获得了图像文件的Content-Length.

可能重要的事情:

Things that may be important:

  • 我没有添加任何html标头,也没有我说过必须使用NSURLSessionUploadTask的教程,我假设NSURLSessionUploadTask为您解决了这个问题?还是这是我的问题?
  • [响应描述]返回200,引号:{URL:(PHP脚本URL)} {状态码:200,标头{连接=保持活动";"Content-Type" =文本/html";日期="2014年1月16日星期四19:58:10 GMT";"Keep-Alive" =超时= 5,最大= 100";服务器= Apache;传输编码" =身份;}}
  • html指定enctype ="multipart/form-data",也许这必须在我的obj-c某个地方使用?
  • 到目前为止,我只在模拟器上运行它
  • 任何帮助将不胜感激!谢谢:)
  • edit,我只编辑了以下代码以显示[request setHTTPMethod:@"POST"],而不是我原来的[request setHTTPMethod:@"PUSH"],但它没有任何改变.

这是目标C

- (void) uploadFile: (NSURL*) localURL toRemoteURL: (NSURL*) phpScriptURL
{
    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:phpScriptURL];
    [request setHTTPMethod:@"POST"];
    NSURLSessionUploadTask* uploadTask = [defaultSession uploadTaskWithRequest:request fromFile:localURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
        if (error == nil)
        {
            NSLog(@"NSURLresponse =%@",  [response description]);
            // do something !!!
        } else
        {
            //handle error
        }
        [defaultSession invalidateAndCancel];
    }];

    self.imageView.image = [UIImage imageWithContentsOfFile:localURL.path]; //to confirm localURL is correct

    [uploadTask resume];
}

这是服务器上的PHP脚本

<?php

        $file = 'log.txt';
        $current = file_get_contents($file);
        $current .= $_FILES["file"]["name"]." is being uploaded. ";  //should write the name of the file to log.txt
        file_put_contents($file, $current);


    ini_set('display_errors',1);
    error_reporting(E_ALL);

   $allowedExts = array("gif", "jpeg", "jpg", "png");
   $temp = explode(".", $_FILES["file"]["name"]);
   $extension = end($temp);

    if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/jpg")
    || ($_FILES["file"]["type"] == "image/pjpeg")
    || ($_FILES["file"]["type"] == "image/x-png")
    || ($_FILES["file"]["type"] == "image/png"))
    //&& ($_FILES["file"]["size"] < 100000) //commented out for error checking
    && in_array($extension, $allowedExts))
      {
      if ($_FILES["file"]["error"] > 0)
        {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
        }
      else
        {
            echo "Upload: " . $_FILES["file"]["name"] . "<br>";
            echo "Type: " . $_FILES["file"]["type"] . "<br>";
            echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
            echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

            if (file_exists("upload/" . $_FILES["file"]["name"]))
              {
              echo $_FILES["file"]["name"] . " already exists. ";
              }
            else
              {
              if (move_uploaded_file($_FILES["file"]["tmp_name"],
              "upload/" . $_FILES["file"]["name"]))
              {
                echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
              }
              else
              {
                echo "Error saving to: " . "upload/" . $_FILES["file"]["name"];
              }

            }
        }
      }
    else
      {
      echo "Invalid file";
      }

?>

,这是调用相同脚本时可以正常工作的html文件

<html>
<body>

    <form action="ios_upload.php" method="post"
    enctype="multipart/form-data">
    <label for="file">Filename:</label>
    <input type="file" name="file" id="file"><br>
    <input type="submit" name="submit" value="Submit">
    </form>

</body>

推荐答案

我在这里回答了同样的问题: https://stackoverflow.com/a/28269901/4518324

I just answered this same question over here:https://stackoverflow.com/a/28269901/4518324

基本上,该文件以二进制文件的形式上传到请求正文中的服务器.

Basically, the file is uploaded to the server in the request body as binary.

要将该文件保存在PHP中,您只需获取请求正文并将其保存到文件中即可.

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

您的代码应如下所示:

Objective-C代码:

- (void) uploadFile: (NSURL*) localURL toRemoteURL: (NSURL*) phpScriptURL
{
    // Create the Request
     NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:phpScriptURL];
    [request setHTTPMethod:@"POST"];

    // Configure the NSURL Session
     NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.upload"];
    [sessionConfig setHTTPMaximumConnectionsPerHost: 1];

     NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:nil];

     NSURLSessionUploadTask* uploadTask = [defaultSession uploadTaskWithRequest:request fromFile:localURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
         if (error == nil)
         {
              NSLog(@"NSURLresponse =%@",  [response description]);
              // do something !!!
         } else
         {
             //handle error
         }
         [defaultSession invalidateAndCancel];
     }];

      self.imageView.image = [UIImage imageWithContentsOfFile:localURL.path]; //to confirm localURL is correct

     [uploadTask resume];
}

PHP代码:

<?php
    // 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 "image/gif; charset=binary":
            // Create filepath
             $file = "upload/image.gif";

            // Write the request body to file
            file_put_contents($file, $request_body);

            break;

        case "image/png; charset=binary":
            // Create filepath
             $file = "upload/image.png";

            // Write the request body to file
            file_put_contents($file, $request_body);

            break;

        default:
            // Handle wrong file type here
            echo $mime_type;
    }
?>

我在这里编写了一个录制音频并将其上传到服务器的代码示例: https://github.com/gingofthesouth/Audio-Recording-Playback-and-上传

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

它显示了从保存在iOS设备上,到上传并保存到服务器的代码.

It shows code from saving on the iOS device, to uploading and saving to the server.

我希望能有所帮助.

这篇关于NSURLSessionUploadTask不将文件传递给php脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 23:05