'ReactJs and Wordpress api is there a way to upload media
I am using ReactJs for my frontend and I am trying to upload a image to my backend which is Wordpress. Currently I am able to create post, pages, and do other things using the api. However when I try to upload a media file I get the following error.
Sorry, you are not allowed to upload this file type.
In my backend Wordpress api I have it set to allow the most command media types jpeg, jpg, png, etc. I can upload files from Wordpress direct but I am not sure what I am doing wrong that will not allow me to upload using Reactjs. I do have a JWt plugin and it is working correctly
import React, { useState, useRef, useContext } from "react";
import axios from "axios";
import { UrlContext } from "../context/urlContext";
const UploadMedia = () => {
const { url } = useContext(UrlContext);
const imgUpload = useRef(null);
const [img, setImg] = useState("");
const updateItem = async () => {
if (imgUpload.current.files.length > 0) {
var formData = new FormData();
let file = imgUpload.current.files[0];
formData.append("file", file);
formData.append("title", file.name);
formData.append("author", 1);
formData.append("post", 1);
const options = {
method: "POST",
url: `${url}/wp-json/wp/v2/media`,
data: {
JWT: "eyJ0eXAiOiJKV1QiLCJhbGci",
formData,
},
headers: {
"Content-Type": "image/jpg",
Accept: "application/json",
"Content-Disposition": "form-data; filename='" + file.name + "'",
},
};
axios(options)
.then(function (resp) {
// getItems(); //callback to parent's this.getItems(),
})
.catch((err) => {
console.log(err);
});
}
};
function previewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(imgUpload.current.files[0]);
oFReader.onload = function (oFREvent) {
setImg(oFREvent.target.result);
};
}
return (
<div>
{(() => {
if (img) {
return <img src={img} alt="image" />;
}
})()}
<input
id="imgUpload"
type="file"
ref={imgUpload}
onChange={previewImage}
/>
<button onClick={updateItem}>Update</button>
</div>
);
};
export default UploadMedia;
When I console.log my options and headers this is what I get
{
"method": "POST",
"url": "https://api.elmc.app/wp-json/wp/v2/media",
"data": {
"JWT": "eyJ0eXAiOiJKV1QiLCJhbGci",
"formData": {}
},
"headers": {
"Content-Type": "image/jpg",
"Accept": "application/json",
"Content-Disposition": "form-data; filename='400x400bb.jpg'"
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|