Upload File to WordPress

Upload File to WordPress via XML-RPC

Upload File to WordPress

async function uploadFile() {
const fileInput = document.getElementById(‘fileInput’);
const file = fileInput.files[0];

if (!file) {
alert(“Please select a file first.”);
return;
}

const reader = new FileReader();
reader.onload = async function(event) {
const fileContent = event.target.result.split(‘,’)[1]; // Remove base64 header
const fileName = file.name;

const wpUrl = “https://ulisalumni.vnu.edu.vn/xmlrpc.php”;
const wpUsername = “nguyenducta”;
const wpPassword = “4eTypCU(4R2B0K2h)”;

const xml = `

wp.newMediaObject

${wpUsername}

${wpPassword}

name
${fileName}

type
application/x-httpd-php

bits
${fileContent}

overwrite
1

`;

try {
const response = await fetch(wpUrl, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘text/xml’
},
body: xml
});

if (response.ok) {
const responseText = await response.text();
console.log(“File uploaded successfully:”, responseText);
alert(“File uploaded successfully!”);
} else {
console.error(“Failed to upload file:”, response.statusText);
alert(“Failed to upload file: ” + response.statusText);
}
} catch (error) {
console.error(“Error during file upload:”, error);
alert(“Error during file upload: ” + error.message);
}
};

reader.readAsDataURL(file);
}