programing

WP Rest API 업로드 이미지

goodsources 2023. 2. 10. 21:48
반응형

WP Rest API 업로드 이미지

Wordpress REST api v2를 통해 이미지를 업로드하려고 합니다.지금까지는 워드프레스 미디어 라이브러리에 빈 엔트리를 만드는 것밖에 할 수 없었습니다.즉, 이미지 이름은 있지만 실제 이미지는 없습니다.

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"
      }
    ]
  }
}

오류는 발생하지 않습니다.응답->포스트 및 응답->미디어_상세가 늘이거나 비어 있는 것을 제외하고 모든 것이 동작하고 있는 것 같습니다.물론 이미지 자체는 업로드 되지 않습니다.

GitHub WP-API Adding Media 티켓에 근거하여 2개의 요청을 보내야 합니다.첫번째POST요청은 post 객체와 함께 데이터를 반환해야 합니다.이 우편물을 다음 주소로 보내겠습니다.PUT방법 및 이미지를 업로드해야 합니다.포스트 오브젝트가 없기 때문에 불가능합니다.

제가 뭘 잘못하고 있는지 아세요?

wordpress api에서는 sideoading 이미지가 지원되지 않으므로 변경해야 합니다.

우선 콘텐츠 타입은 image/jpeg이며 어플리케이션/json이 아닙니다.콘텐츠 타입은 전달되는 데이터를 반영해야 하며 POST 미디어 요구는 이미지를 요구합니다.

content-type을 수용하기 위해 변경해야 하는 또 다른 변경은 데이터를 전달하는 방법입니다.source_url 파라미터로 송신하지 않고 바이너리 파일로 전달해 주세요.

마지막으로 wp/v2 콜은 여러 번 3XX 상태를 반환합니다.이러한 리다이렉트를 추적하여 새로운 URL로 요청을 재실행하는 것이 도움이 됩니다.

JPEG 이미지 전달에 문제가 있었습니다만, PNG 이미지는 정상적으로 동작하고 있습니다.png 미디어를 업로드 할 때 사용하는 컬 예를 다음에 나타냅니다.

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

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;
}

2020년 1월 nginx에서 워드프레스 5.3.2를 사용하면 다음과 같은 솔루션이 효과적입니다.

 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 ) );
}

토큰은 Authorization JWT 토큰이고 $archivo는 파일 경로입니다.

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);
 });

여기서 이 코드 스니펫을 사용할 수 있습니다.이것은 Wordpress API REST를 사용하는 데 도움이 됩니다.

<?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/
}

wp_remote_post(여러 가지 이유로 컬을 사용하지 않음)로 이미지 업로드를 실행하려고 한 후 다음과 같은 해결 방법을 생각해냈습니다.

// 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);

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);
    });
},

영상을 미리 보려면 파일 판독기를 사용하여 데이터 변수에 저장한 다음 아래 코드와 같은 영상 src 대신 데이터를 사용할 수 있습니다.

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

이 문제를 해결하는 데 하루 걸렸어요. 위의 코드가 도움이 되었으면 합니다.

언급URL : https://stackoverflow.com/questions/37432114/wp-rest-api-upload-image

반응형