Multipart form file upload POST PHP cURL

前端 未结 4 560
慢半拍i
慢半拍i 2021-01-15 02:30

I am wanting to send a file via http POST using PHP and cURL.

The form POST was working ok with basic fields besides the file being posted with \'application/json\'.

4条回答
  •  一向
    一向 (楼主)
    2021-01-15 03:14

    Hi I have figured out the problem.

    My params were not set correct on the api endpoint. Need to set a note_id(c_id)

    But issue I am having now is posting all data at once. I am posting file after the note has been created thus generating the note id for me for posting file. Can anyone help with that? I can post a new question.

    See updated code below:

    //$orgID = (is_numeric($_POST['orgID']) ? (int)$_POST['orgID'] : 0);
    //$noteTitle = (isset($_POST['noteTitle']) ? $_POST['noteTitle'] : null);
    //$noteBody = (isset($_POST['noteBody']) ? $_POST['noteBody'] : null);
    
    $noteID = (isset($_POST['noteID']) ? $_POST['noteID'] : null);
    
    $localFile = $_FILES['file']['tmp_name'];
    $fp = fopen($localFile, 'r');
    
    $curl = curl_init();
    
    $cfile = new CURLFILE($_FILES['file']['tmp_name'], $_FILES['file']['type'], $_FILES['file']['name']);
    $data = array();                
    //$data["TITLE"] = "$noteTitle";
    //$data["BODY"] = "$noteBody";
    //$data["LINK_SUBJECT_ID"] = "$orgID";
    //$data["LINK_SUBJECT_TYPE"] = "Organisation";        
    $data['FILE_ATTACHMENTS'] = $cfile;
    
    curl_setopt_array($curl, array(
      CURLOPT_UPLOAD => 1,
      CURLOPT_INFILE => $fp,
      CURLOPT_NOPROGRESS => false, 
      CURLOPT_BUFFERSIZE => 128,
      CURLOPT_INFILESIZE => filesize($localFile),
      CURLOPT_URL => "https://api.insight.ly/v2.1/Notes/?c_id=" . $noteID . "&filename=" . $_FILES['file']['name'],
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => $data,      
      CURLOPT_HTTPHEADER => array(
        "authorization: Basic xxx",
        "cache-control: no-cache",
        "content-type: multipart/form-data",
        "postman-token: xxx"
      ),
    ));
    $response = curl_exec($curl);
    $err = curl_error($curl);
    
    curl_close($curl);
    
    if ($err) {
      echo "cURL Error #:" . $err;
    } else {
      echo $response;
    }
    

    HTML

    // // //

    If anyone is interested this is my solution for using fpdf to generate a PDF document from the web form then auto send, instead of the file upload. FPDF file ---> send via CURL automatically NOT with file upload

提交回复
热议问题