在邮递员中使用 php curl 将文件上传到 Nextcloud 但上传的文件为空

2022-01-22 00:00:00 postman curl php yii2 nextcloud

已解决这是我的代码,我正在尝试使用它的 api 将文件上传到 nextcloud,我上传了文件但它是空的.

SOLVED This is my code, I'm trying to upload a file to nextcloud using its api, I uploaded the file but it is empty.

我所做的是使用 fopen fread 来保存文件内容并通过 postfields 将其发送到 nextcloud:

What I did was to use fopen an fread to save th file content and send it by postfields to nextcloud:

public function actionSubirArchivoNube()
    {
        $response = null;
        if(Yii::$app->request->isPost){

            $body = Yii::$app->request->getRawBody();
            $body = Json::decode($body);


            $datosNube = $body['CredencialesNube'];
            $username = $datosNube['username'];
            $password = $datosNube['password'];
            $servidorNube = $datosNube['server_name'];
            $camino = $datosNube['pathArchivo'];
            $filename = basename($camino);

            //Se tiene el contenido del archivo
            $gestor = fopen($camino, "r");
            $contenido = fread($gestor, filesize($camino));
            fclose($gestor);

            //Se tiene la url que responde a la nube y los headers
            $url = $servidorNube .'/remote.php/dav/files/admin/' . $filename;
            $headers = array('Authorization: Basic ' . base64_encode("$username:$password"),
                'OSC-APIRequest: true', 'Content-Type: text/html; charset=UTF-8');

            $options = array(
                CURLOPT_SAFE_UPLOAD => true,
                CURLOPT_HEADER => true,
                CURLOPT_CUSTOMREQUEST => "PUT",
                CURLOPT_URL => $url,
                CURLOPT_HTTPHEADER => $headers,
                CURLOPT_POSTFIELDS => $contenido,
                CURLOPT_SSL_VERIFYPEER=> false
            );

            $curl = curl_init();
            curl_setopt_array($curl, $options);
            $response = curl_exec($curl);
            curl_close($curl);
            $response = json_decode($response,true);

            return $response;
        }       
    }

推荐答案

这段代码对我有用

$nombre_fichero = "C:\pruebas\Documento_1.pdf";
$gestor = fopen($nombre_fichero, "rb");
$contenido = fread($gestor, filesize($nombre_fichero));
fclose($gestor);
    
$login = 'usuario';
$password = 'clave';
$url = 'https://dominio.com/remote.php/dav/files/usuario/folder1/D4.pdf';

$options = array(
CURLOPT_SAFE_UPLOAD => true,
CURLOPT_HEADER => true,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_URL => $url,
CURLOPT_POSTFIELDS => $contenido,
CURLOPT_SSL_VERIFYPEER=> false,
CURLOPT_RETURNTRANSFER=> 1,
CURLOPT_HTTPAUTH=>CURLAUTH_BASIC,
CURLOPT_USERPWD=> $login.':'.$password,
CURLOPT_HTTPHEADER=>array('OCS-APIRequest: true')
);

$curl = curl_init();
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
curl_close($curl);


echo "<pre>";
echo $response;
echo "</pre>";

相关文章