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)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.