从变量上传文件到服务

时间:2018-08-12 12:14:23

标签: php

我有用于将文件上载到某些服务的下一个代码,我想更改代码,以便可以从变量发送文件数据,而无需从文件上载。

任何想法怎么做?

(例如:$ file_content =“ content-goes-here”;然后直接从变量上传内容)

$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $url);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlHandle, CURLOPT_USERPWD, "$applicationId:$password");
curl_setopt($curlHandle, CURLOPT_POST, 1);
curl_setopt($curlHandle, CURLOPT_USERAGENT, "PHP Cloud SDK Sample");
curl_setopt($curlHandle, CURLOPT_FAILONERROR, true);
$post_array = array();
if ((version_compare(PHP_VERSION, '5.5') >= 0)) {
    $post_array["my_file"] = new CURLFile($filePath);
} else {
    $post_array["my_file"] = "@".$filePath;
}
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $post_array); 
$response = curl_exec($curlHandle);
if ($response == FALSE) {
    $errorText = curl_error($curlHandle);
    curl_close($curlHandle);
    die($errorText);
}
$httpCode = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
curl_close($curlHandle);
// Parse xml response
$xml = simplexml_load_string($response);
if ($httpCode != 200) {
    if (property_exists($xml, "message")) {
        die($xml->message);
    }
    die("unexpected response ".$response);
}

1 个答案:

答案 0 :(得分:0)

是的,可以。您只需要设置以下内容:

curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $fileContents);

别忘了设置Content-type标头:

curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: image/jpeg']);

或者您可以将请求的正文创建为字符串并发送许多文件。看看这个答案:PHP Curl post with file attachment; custom content-type header