PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

[FIXED] How to upload image to wordpress rest api using axios in nuxtjs and vuejs

 October 13, 2022     axios, nuxt.js, vue.js, wordpress     No comments   

Issue

I want to upload image from my nuxtjs app to WordPress media library using WordPress rest API, with below code I get below error:

"Sorry, you are not allowed to upload this file type."

    onUpload() {
const fd = new FormData();
fd.append("image", this.selectedFile, this.selectedFile.name);

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

As I readed other answers i should send image binary instaed of form data but i dont know how can i do this.in this post described to send image binary but there is no vuejs example


Solution

finally, I find out the solution in WordPress for sending images you should append a title and caption also I had a problem with my code fd constant should not be in curly braces below code works fine

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


Answered By - pedram
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing