通过cURL上传到BrickFTP包含内容处置标头

时间:2018-03-22 19:37:26

标签: php curl amazon-s3

我正在尝试使用带有PHP cURL库的API将文件上传到BrickFTP。我可以上传文件,但内容处理标题最终位于上传文件的顶部。 (BrickFTP上传到Amazon S3)。我的问题与this question非常相似,但我无法将答案转换为PHP。

// Authenticate with Session
$ch = curl_init();
$postData = json_encode([
   'username' => 'xxx',
   'password' => 'xxx'
]);
curl_setopt($ch, CURLOPT_URL, "https://SUBDOMAIN.brickftp.com/api/rest/v1/sessions.json");
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json", "Accept: application/json"]);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

$result = curl_exec($ch);
$error = curl_error($ch);

$result = json_decode($result);
$apiID = $result->id;

// Step 1: Get the upload URI
$remotePath = 'https://SUBDOMAIN.brickftp.com/api/rest/v1/files/' . basename($this->remotePath);
$postData = json_encode([
   'action' => 'put',
]);
curl_setopt($ch, CURLOPT_URL, $remotePath);
curl_setopt($ch, CURLOPT_COOKIE, "BrickAPI={$apiID}");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

$result = curl_exec($ch);
$error = curl_error($ch);

$result = json_decode($result);
$headers = empty($result->headers) ? 0 : $result->headers;

// Step 2: Upload the file
$fileSize = filesize($this->localPath);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$finfo = finfo_file($finfo, $this->localPath);
$cFile = new CURLFile($this->localPath, $finfo, basename($this->localPath));
$postData = ['file' => $cFile];
curl_setopt($ch, CURLOPT_URL, $result->upload_uri);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_HEADER, $headers);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Length: {$fileSize}", "Content-Type: text/plain"]);
curl_setopt($ch, CURLOPT_INFILESIZE, $fileSize);

$result = curl_exec($ch);
$error = curl_error($ch);

// Step 3: Complete the request
...

文件上传成功,但添加到顶部:

--------------------------af8ccf12ca11d3f7
Content-Disposition: form-data; name="0"; filename="my-file.csv"
Content-Type: text/plain

首先我将Content-type设置为multipart/form-data,但谷歌搜索,我读到有些人通过将Content-type设置为text/plain来修复此问题;那对我没有用。我还尝试仅使用@/filepath/my-file.csv作为file$postData的值,但结果是HTTP/1.1 400 Bad Request

1 个答案:

答案 0 :(得分:0)

所以看起来我只需要将数据作为字符串发送,如下所示:

$postData = file_get_contents($this->localPath);

可能重复:PHP Curl post a file without header