0

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

pedram
  • 181
  • 2
  • 8
  • Try to upload to your WordPress API with something like Postman to be sure that it is properly working. Then, use a search engine to find out how to upload a file, there are quite a few tutorials that are working great. – kissu Aug 13 '22 at 13:55
  • I uploaded the file successfully using postman but with Axio's request I got an error – pedram Aug 13 '22 at 14:06

1 Answers1

1

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);
    });
},
pedram
  • 181
  • 2
  • 8