ios Upload Image and Text using HTTP POST

后端 未结 10 1981
执笔经年
执笔经年 2020-11-22 08:27

Thanks for reading.

I am new to iOS and I am trying to upload an Image and a text using multi-part form encoding in iOS.

The curl

10条回答
  •  感情败类
    2020-11-22 08:48

    I can show you an example of uploading a .txt file to a server with NSMutableURLRequest and NSURLSessionUploadTask with help of a php script.

    -(void)uploadFileToServer : (NSString *) filePath
    {
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://YourURL.com/YourphpScript.php"]];
    [request setHTTPMethod:@"POST"]; 
    [request addValue:@"File Name" forHTTPHeaderField:@"FileName"];
    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject];
    
    NSURLSessionUploadTask* uploadTask = [defaultSession uploadTaskWithRequest:request fromFile:[NSURL URLWithString:filePath] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
                                          {
                                              NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                              if (error || [httpResponse statusCode]!=202)
                                              {
    
                                                  //Error
                                              }
                                              else
                                              {
                                                 //Success
                                              }
                                              [defaultSession invalidateAndCancel];
                                          }];
    [uploadTask resume];
    }
    

    php Script

     $value) 
    {
        if ($FileName=="FileName") 
        {
            $header=$value;
            break;
        }
    }   
    $uploadedDir = "directory/";
    @mkdir($uploadedDir);
    file_put_contents($uploadedDir."/".$FileName.".txt",
    $request_body.PHP_EOL, FILE_APPEND);
    header('X-PHP-Response-Code: 202', true, 202);  
    ?>       
    

提交回复
热议问题