PHP卷上传文件

时间:2017-02-20 20:29:56

标签: php curl

我正在尝试使用PHP将文件上传到API。除了文件,我需要提供其他参数。我目前的代码如下:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);

curl_setopt($ch, CURLOPT_PUT, 1);
$post = array(
    'file'        => '@' . realpath('filename'),
    'other_parameter'  => ''
);

curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array('Content-Type: multipart/form-data');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERPWD, $user . ":" . $pass);
$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

服务器标头响应: HTTP/1.1 422 status code 422 Cache-Control: no-cache Content-Type: application/json; charset=utf-8 Status: 422 Unprocessable Entity Vary: Origin X-Content-Type-Options: nosniff X-Xss-Protection: 1; mode=block Content-Length: 106 Connection: keep-alive

此外,我收到文件字段不能为空的消息。

2 个答案:

答案 0 :(得分:1)

以下是您问题的答案(因为它是重复的问题!):

how to upload file using curl with php

还可以看一下这里的链接: http://php.net/manual/en/function.curl-file-create.php

答案 1 :(得分:0)

function ftp_upload($localfile,$ftpHost,$ftpUsername,$ftpPassword){
    $ch=curl_init();
    $fp=fopen($localfile,'r');
    curl_setopt($ch,CURLOPT_URL,"ftp://".$ftpUsername.':'.$ftpPassword.'@'.$ftpHost.'/htdocs/'.$localfile);
    curl_setopt($ch,CURLOPT_UPLOAD,1);
    curl_setopt($ch,CURLOPT_INFILE,$fp);
    curl_setopt($ch,CURLOPT_INFILESIZE,filesize($localfile));
    curl_exec ($ch);
    $error_no=curl_errno($ch);
    curl_close ($ch);
    if($error_no==0){
        $message='File uploaded successfully.';
    }
    else{
        $message='File upload error: $error_no';
    }
    return $message;
}
echo ftp_upload('test.zip','ftp.hello.net','user','123456');