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);
}
解决方案
是的你可以。您只需像这样设置内容:
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $fileContents);
并且不要忘记设置Content-type
标题:
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: image/jpeg']);
或者您可以将请求的正文创建为字符串并发送许多文件。看看这个答案:PHP Curl post with file attachment;自定义内容类型标头
推荐阅读
- python - 将 Python 上的多个列与单个值匹配
- php - EasyAdmin 3:嵌套表单(另一个集合中的调用)
- python - Pandas.to_datetime() 试图在 DataFrame 的切片副本上设置值
- httpclient - Vert.x - 如何知道哪个连接被关闭
- mysql - 选择导出模式时导出进度出错
- android - 将 Javascript 注入 Android
- vue.js - Vue 模板字符串以编程方式编译为 html 字符串
- python - 将文件从 Google Cloud Storage 下载到远程服务器
- android - 我们如何使用 API 在 node.js 服务器上识别和验证平台请求(web、android、ios)?
- javascript - JavaScript 总价目表不显示