wordpress WP Rest API上传图像

sg3maiej  于 2022-12-03  发布在  WordPress
关注(0)|答案(7)|浏览(167)

我正在尝试通过WordPress REST API v2上传图片。到目前为止,我所做的一切都是在WordPress媒体库中创建空条目。这意味着它们有图片名称,但没有实际的图片。
POST请求:

http://localhost/wordpress/wp-json/wp/v2/media

Authorization: Basic d29yZHByZXNzOndvcmRwcmVzcw==
Content-Type: application/json
Content-Disposition: attachment;filename=map2.jpg

{
  "source_url" : "file:///C:/Users/x/Desktop/map2.jpg"
}

回应:

{
  "id": 127,
  "date": "2016-05-25T08:43:30",
  "date_gmt": "2016-05-25T08:43:30",
  "guid": {
    "rendered": "http://localhost/wordpress/wp-content/uploads/2016/05/map2-3.jpg",
    "raw": "http://localhost/wordpress/wp-content/uploads/2016/05/map2-3.jpg"
  },
  "modified": "2016-05-25T08:43:30",
  "modified_gmt": "2016-05-25T08:43:30",
  "password": "",
  "slug": "map2-3",
  "status": "inherit",
  "type": "attachment",
  "link": "http://localhost/wordpress/map2-3/",
  "title": {
    "raw": "map2-3",
    "rendered": "map2-3"
  },
  "author": 1,
  "comment_status": "open",
  "ping_status": "closed",
  "alt_text": "",
  "caption": "",
  "description": "",
  "media_type": "image",
  "mime_type": "image/jpeg",
  "media_details": {},
  "post": null,
  "source_url": "http://localhost/wordpress/wp-content/uploads/2016/05/map2-3.jpg",
  "_links": {
    "self": [
      {
        "href": "http://localhost/wordpress/wp-json/wp/v2/media/127"
      }
    ],
    "collection": [
      {
        "href": "http://localhost/wordpress/wp-json/wp/v2/media"
      }
    ],
    "about": [
      {
        "href": "http://localhost/wordpress/wp-json/wp/v2/types/attachment"
      }
    ],
    "author": [
      {
        "embeddable": true,
        "href": "http://localhost/wordpress/wp-json/wp/v2/users/1"
      }
    ],
    "replies": [
      {
        "embeddable": true,
        "href": "http://localhost/wordpress/wp-json/wp/v2/comments?post=127"
      }
    ]
  }
}

我没有得到错误,一切似乎都在工作,除了响应-〉post和响应-〉media_details不是null就是空。当然图片本身没有上传。
基于这个GitHub WP-API Adding Media票证,我应该发送2个请求。第一个POST请求应该返回带有post对象的数据。我将通过PUT方法发送这个post对象,并且应该上传图像...因为我没有post对象,这是不可能的。
知道我做错了什么吗?

esbemjvw

esbemjvw1#

wordpress api不支持旁载图片,所以你必须做一些修改。
首先,您的content-type应该是image/jpeg而不是application/json,请记住,内容类型应该反映您传递的数据,POST媒体请求需要图像。
为了适应content-type,您必须进行的另一个更改是传递数据的方式。不要使用source_url参数发送数据,而应尝试将其作为二进制文件传递。
最后我要提到的一件事是,wp/v2调用在一些情况下返回3XX状态,这将是有用的,按照这些重定向和重做这些请求到那些新的url。
我在传递JPEG图像时遇到了一些问题,但PNG图像已经很好地工作了。下面是我用来上传PNG媒体的一个curl示例:

curl --request POST \
--url http://www.yoursite.com/wp-json/wp/v2/media \
--header "cache-control: no-cache" \
--header "content-disposition: attachment; filename=tmp" \
--header "authorization: Basic d29yZHByZXNzOndvcmRwcmVzcw==" \
--header "content-type: image/png" \
--data-binary "@/home/web/tmp.png" \
--location
ijnw1ujt

ijnw1ujt2#

我的工作答案使用PHP cUrl

<?php

$curl = curl_init();

$data = file_get_contents('C:\test.png');

curl_setopt_array($curl, array(
  CURLOPT_URL => "http://woo.dev/wp-json/wp/v2/media",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_HTTPHEADER => array(
    "authorization: Basic XxxxxxxXxxxxXx=",
    "cache-control: no-cache",
    "content-disposition: attachment; filename=test.png",
    "content-type: image/png",
  ),
  CURLOPT_POSTFIELDS => $data,
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
8ehkhllq

8ehkhllq3#

在2020年1月使用WordPress 5.3.2与nginx的解决方案,为我工作是:

function uploadFile($token, $archivo) {
    $file = file_get_contents( $archivo );
    $mime = mime_content_type( $archivo );
    $url =  BASEAPI. 'wp-json/wp/v2/media';
    $ch = curl_init();

    curl_setopt( $ch, CURLOPT_URL, $url );
    curl_setopt( $ch, CURLOPT_POST, 1 );
    curl_setopt($ch,  CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt( $ch, CURLOPT_POSTFIELDS, $file );
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt( $ch, CURLOPT_HTTPHEADER, [
        'Content-Type: '.$mime,
        'Content-Disposition: attachment; filename="'.basename($archivo).'"',
        'Authorization: Bearer ' .$token,
    ] );
    $result = curl_exec( $ch );
    curl_close( $ch );
    print_r( json_decode( $result ) );
}

该标记是授权JWT标记,$archivo是文件路径。

iswrvxsc

iswrvxsc4#

对于任何寻找JS解决方案的人,这里是我如何使用Axios使其工作的。我将跳过授权实现,因为周围有几个选项(oAuth、JWT、Basic)。

const fs = require('fs');
const axios = require('axios');

axios({
  url: 'http(s)://{your-wp-domain}/wp-json/wp/v2/media',
  method: 'POST',
  headers: {
    'Content-Disposition':'attachment; filename="file.jpg"',
     Authorization: {your-authorization-method},
    'Content-Type':'image/jpeg'
    },
    data: fs.readFileSync('path/to/file.jpg', (err, data) => {
      if (err) {
        console.log(err);
      }
    });
})
 .then(res => {
   console.log(res.data);
 })
 .catch(err => {
   console.log(err);
 });
pieyvz9o

pieyvz9o5#

在尝试用wp_remote_post上传图片后(不想使用curl,有几个原因),我提出了以下解决方案:

// Upload image to wordpress media library

$file = @fopen( 'image.jpg', 'r' );
$file_size = filesize( 'image.jpg' );
$file_data = fread( $file, $file_size );
$args = array(
    'headers'     => array(
        'Authorization' => 'Basic ' . base64_encode( 'USERNAME:PASSWORD' ),
        'accept'        => 'application/json', // The API returns JSON
        'content-type'  => 'application/binary', // Set content type to binary
        'Content-Disposition' => 'attachment; filename=nameoffileonserver.jpg'
    ),
    'body'        => $file_data
    );


$api_response = wp_remote_post( 'http://myserver.com/wp-json/wp/v2/media', $args);
yquaqz18

yquaqz186#

在这里你可以使用这个代码片段。

<?php
//Add this to your function.php
function upload_image( $imageID, $login ) {
  $request_url = 'https://DOMAINNAME.com/wp-json/wp/v2/media'; //change the domainname
    $image_file_path = get_attached_file($imageID); //change this to your file meda path if your not throwing media file to other server
  $image = file_get_contents( $image_file_path );
    $mime = mime_content_type( $image_file_path );

  $api_media_response = wp_remote_post( $request_url, array(
        'headers' => array(
            'Authorization' => 'Basic ' . base64_encode( $login ), //login format USERNAME:PASSWORD
            'Content-Disposition' => 'attachment; filename='.basename($image_file_path).'',
            'Content-Type' => $mime
        ),
        'body' => $image
    ) );

  //this function return wp_remote_post
  // more info => https://developer.wordpress.org/reference/functions/wp_remote_post/
}
iqxoj9l9

iqxoj9l97#

如果你想用nuxtjs或vuejs上传一个图片到WordPress rest API,你可以使用下面的代码:

在模板中:

<input style="display: none;" type="file" @change="onFileSelected"
<button @click="onUpload" />

在数据中:

data() {
return {
  selectedFile: null,
  previewImage: null
};}

在方法中:

onFileSelected(event) {
  this.selectedFile = event.target.files[0];
   }

   onUpload() {
const fd = new FormData();
fd.append("file", this.selectedFile, this.selectedFile.name);
fd.append("title", "pedram");
fd.append("caption", "this is caption");

/* file reader for prview image */
const reader = new FileReader();
reader.readAsDataURL(this.selectedFile);
reader.onload = e =>{
                this.previewImage = e.target.result;
};
/* set request header */
const headers = {
  'Content-Disposition':`attachment; filename=${this.selectedFile.name}`,
   Authorization: "Bearer" + this.$cookiz.get("AdminToken"),
  'content-type': 'image' 
};

  this.$axios.post('/wp-json/wp/v2/media', fd, { headers })
    .then(res => {
      console.log(res);
    })
    .catch(err => {
      console.log(err);
    });
},

如果你想预览图像,你可以使用文件读取器,并将其存储在一个数据变量中,然后使用数据代替图像源代码,如下面的代码:

<img @click="$refs.fileInput.click()" v-if="previewImage" :src="previewImage" alt="" class="w-100" />

我花了一天的时间来解决这个问题,我希望上面的代码能有所帮助

相关问题