dqnqpqv3841 2018-08-12 12:14
浏览 51

从变量[duplicate]上传文件到服务

This question already has an answer here:

I've the next code for uploding a file to some service, I would like to change the code so I can send the file data from variable and no uploading it from a file.

Any idea how to do so?

(For example : $file_content = "content-goes-here"; and upload the content directly from the variable)

$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);
}
</div>
  • 写回答

1条回答 默认 最新

  • doufanglian7585 2018-08-12 13:20
    关注

    Yes, you can. You have just to set content like this:

    curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $fileContents);
    

    And don't forget to set Content-type header:

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

    Or you can create request's body as string and send many files. Look at this answer: PHP Curl post with file attachment; custom content-type header

    评论

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图