cURL将请求php发布到春季

时间:2020-01-08 13:43:24

标签: php spring curl post

我必须使用PHP和cURL将文件数组发送到spring服务器。

这是弹簧控制器:

@RequestMapping(value = "/upload/teacher" ,method = RequestMethod.POST) 
public HttpStatus uploadFiles(@RequestParam("files") MultipartFile[] inputFiles, 
                              @RequestParam("assignmentID") String assignmentID) throws IOException { ... }

PHP cURL:

<?php 
$filenames = array(pathfile1, pathfile2);

$postparameters = array(
  'files' =>  array(
                    new CURLFile($filenames[0], "text/plain", pathinfo($filenames[0], PATHINFO_BASENAME)),
                    new CURLFile($filenames[1], "text/plain", pathinfo($filenames[1], PATHINFO_BASENAME))
                  ),
  'assignmentID' => "0008"         
  );

print_r($postparameters);


//init curl
$url = "http://localhost:8090/upload/teacher";


$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_POST => true,
  CURLOPT_POSTFIELDS => $postparameters,
  CURLOPT_HTTPHEADER => array(
    "Content-Type: multipart/form-data"
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

但是使用此代码,后端无法接收任何内容。

如果我从终端发送了curl请求,它将起作用:

 curl -F files=@"pathfile1","pathfile2" -F assignmentID="1" http://localhost:8090/upload/teacher

它也适用于邮递员:

https://i.stack.imgur.com/Mo3yg.png] 1

有人可以告诉我为什么当我从php运行请求时,如果后端没有收到文件吗?

1 个答案:

答案 0 :(得分:0)

如果用@CrossOrigin注释spring控制器方法会怎样?

@CrossOrigin
@RequestMapping(value = "/upload/teacher" ,method = RequestMethod.POST) 
public HttpStatus uploadFiles(@RequestParam("files") MultipartFile[] inputFiles, 
                              @RequestParam("assignmentID") String assignmentID) throws IOException { ... }