I have an input
file in HTML to upload an image
<input type="file" id="upload-image">
I want to upload my image to my local Apache webserver with AJAX like this
$('#upload-image').change(function(e){
var file = e.target.files[0];
var imageType = /image.*/;
if (!file.type.match(imageType))
return;
var form_data = new FormData();
form_data.append('file', file);
console.log(form_data);
$.ajax({
url: 'http://localhost/upload.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
I already moved my upload.php
to /var/www/html/
, and when I access it on browser, it does exist on my local webserver. But when I try to upload my image, the browser throws this error:
XMLHttpRequest cannot load http://localhost/upload.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
This is my upload.php
:
<?php
header('Access-Control-Allow-Origin: *');
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
I thought I already added Access-Control-Allow-Origin
header then it would work. How can I make it work?