Drupal使用drupal_http_request表单api文件上传

时间:2013-09-01 22:31:33

标签: forms drupal file-upload

我正在尝试使用drupal_http_request通过发布请求将以drupal格式上传的文件发布到另一台服务器。

我不确定我在哪里犯了错误,但文件似乎没有发布。我该怎么办?

我使用以下代码。

 $options = array(
  'method' => 'POST',
  'data' => drupal_http_build_query($data),
  'timeout' => $connect_ariba_values['timeout'],
  'headers' => array('Content-Type' => 'multipart/form-data'),
);

$response = drupal_http_request($url, $options);

multipart / form-data似乎不起作用。

1 个答案:

答案 0 :(得分:2)

来源:https://drupal.org/user/194073

<?php 
$boundary = md5(uniqid());
$post_data = array(
  'name' => 'Ayesh',
  'file' => '/var/www/test/test.png',
);

$options = array(
  'method' => 'POST',
  'data' => multipart_encode($boundary, $post_data),
  'timeout' => $connect_ariba_values['timeout'],
  'headers' => array('Content-Type' => "multipart/form-data; boundary=$boundary"),
);
$response = drupal_http_request($url, $options);

// Function to encode text data.
function multipart_enc_text($name, $value){
  return "Content-Disposition: form-data; name=\"$name\"\r\n\r\n$value\r\n";
}

// Function to multipart encode a file from a give path.
function multipart_enc_file($path){
  if (substr($path, 0, 1) == "@") $path = substr($path, 1);
  $filename = basename($path);
  $mimetype = "application/octet-stream";
  $data = "Content-Disposition: form-data; name=\"file\"; filename=\"$filename\"\r\n"; // "file" key.
  $data .= "Content-Transfer-Encoding: binary\r\n";
  $data .= "Content-Type: $mimetype\r\n\r\n";
  $data .= file_get_contents($path) . "\r\n";
  return $data;
}

// base function to encode a data array.
function multipart_encode($boundary, $params){
  $output = "";
  foreach ($params as $key => $value){
    $output .= "--$boundary\r\n";
    if ($key == 'file'){
      $output .= multipart_enc_file($value);
    } else $output .= multipart_enc_text ($key, $value);
  }
  $output .="--$boundary--";
  return $output;
}

在服务器中,文件将在$_FILES['file']中可用,其他POST数据将在其相关密钥中可用。

我没有测试代码。我刚刚在drupal论坛中找到了代码,将其更改为与Drupal 6和7一起使用。