duansaoguan7955
2018-05-11 08:31 阅读 96
已采纳

在php中使用curl添加表单数据

I'm trying to convert this curl request to PHP:

curl -X POST \
    --form fileItems[0].fileToUpload=@"/path/to/file1.txt"  \
    --form fileItems[0].path="/path1/path2/"    \
    --form fileItems[0].replacing=true  \
    --form fileItems[1].fileToUpload=@"/path/to/file2.txt"  \
    --form fileItems[1].path="/path1/path3/"    \
    --form fileItems[1].replacing=true  \
    http://example.com/files

Here is my code:

$ch=curl_init("http://example.com/files");

$cfile= new CURLFile($_FILES['uploaded_files']['tmp_name'],
                     $_FILES['uploaded_files']['type'],
                     $_FILES['uploaded_files']['name']);

$data=array("fileItems" => array("fileToUpload" => $cfile,
                                 "path" => "/",
                                 "replacing" => true
                                ));

After uploading a file and trying to send it to the server I get this message:

Notice: Array to string conversion in C:\...\uploadToBacktory.php on line 48

line 48:

curl_setopt($ch,CURLOPT_POSTFIELDS, $data);

API server error:

{"timestamp":1526026978184,"status":400,"error":"Bad Request","exception":"org.springframework.validation.BindException","errors":[{"codes":["typeMismatch.fileUploadRequest.fileItems","typeMismatch.fileItems","typeMismatch.java.util.List","typeMismatch"],"arguments":[{"codes":["fileUploadRequest.fileItems","fileItems"],"arguments":null,"defaultMessage":"fileItems","code":"fileItems"}],"defaultMessage":"Failed to convert property value of type 'java.lang.String' to required type 'java.util.List' for property 'fileItems'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'ir.pegahtech.backtory.cdn_api.models.controllers.files.FileUploadItem' for property 'fileItems[0]': no matching editors or conversion strategy found","objectName":"fileUploadRequest","field":"fileItems","rejectedValue":"Array","bindingFailure":true,"code":"typeMismatch"}],"message":"Validation failed for object='fileUploadRequest'. Error count: 1","path":"/files"}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dpppic5186 dpppic5186 2018-05-11 10:06

    problem solved by changing $data variable to this:

    $data=['fileItems[0].path' => '/', 'fileItems[0].replacing' => true, 'fileItems[0].fileToUpload' => $cfile];
    
    点赞 评论 复制链接分享

相关推荐