Am currently local host, and my HTML looks like this:
<form method="POST" id="myForm">
<input type="file" name="sample_image" id="sample_image">
<div id="uploaded_image"></div>
<button type="submit">Upload</button>
</form>
JavaScript:
const sample_image = document.getElementsByName("sample_image")[0];
sample_image.addEventListener('submit', e => {
e.preventDefault()
upload_image(sample_image.files[0])
})
const upload_image = (file) => {
if(!['image/jpeg', 'image/png'].includes(file.type)) {
document.getElementById("uploaded_image").innerHTML = '<div class="alert">Only .jpg are allowed</div>';
document.getElementsByName('sample_image')[0].value = '';
console.log("image format");
return;
}
if(file.size > 2 * 1024 * 1024) {
document.getElementById('uploaded_image').innerHTML = '<div>File must be ess than 2MB</div>';
document.getElementsByName('sample_image')[0].value = '';
console.log("image size");
return;
}
const form_data = new FormData();
form_data.append("sample_image", file);
console.log(form_data)
fetch("/upload.php", {
method: "POST",
body: form_data
}).then(function(response){
return response.json();
}).then(function(responseData){
document.getElementById("uploaded_image").innerHTML = '<p>Image uploaded successfully <img src="'+responseData.image_source+'" /></p>';
document.getElementsByName("sample_image")[0].value = '';
})
}
PHP:
if(!isset($_FILES['sample_image'])) {
$extension = pathinfo($_FILES['sample_image']['name'], PATHINFO_EXTENSION);
$new_name = time() . '.' . $extension;
move_uploaded_file($_FILES['sample_image']['tmp_name'], 'images/' . $new_name);
$data = [
'image_source' => 'images/' . $new_name
];
echo json_encode($data);
}
When I submit the form, I get a 405 error:
Post method not allowed
How best can I upload files using JavaScript?
Amongst many articles I ran into this and I still can’t see why the error message.