Posting file via wp_remote_post

发布于 11 天前  63 次阅读

For several reasons I don't want to use curl, and I have known that WordPress has methods for HTTP request, so I choose wp_remote_post(), which allows you to send an HTTP post request, and return an array. Here's the code example:

$upload_url = "URL_YOUR_UPLOAD_FILE_TO";
$local_file = "PATH/TO/FILE";
$filename = basename($local_file);
$name = $local_file;  //name of Form Control
$Boundary = wp_generate_password();  //split signal, see:
$bits = file_get_contents($local_file);

$args = array(
    "headers" => "Content-Type: multipart/form-data; boundary=$Boundary",
    "body" => "--$Boundary\r\nContent-Disposition: form-data; name=\"$name\"; filename=\"$filename\"\r\n$bits\r\n--$Boundary--"

$response = wp_remote_post($upload_url, $args);
if (!is_wp_error($response)) {
    $reply = $response["body"];  //the remote server's reply