1

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?

necroface
  • 3,365
  • 10
  • 46
  • 70
  • And you're running everything on a webserver, like wamp, easyphp etc. – adeneo Oct 15 '16 at 17:43
  • Read my answer here, maybe it will help. http://stackoverflow.com/questions/28547288/no-access-control-allow-origin-header-is-present-on-the-requested-resource-err/38000615#38000615 – dkruchok Oct 15 '16 at 17:45
  • @dkruchok Thank you. It does send. But I don't know why my `form_data` is still completely empty while `file` is not null when I `console.log` both of them – necroface Oct 15 '16 at 17:56
  • need to properly implement CORS and not check for files during OPTIONS request – charlietfl Oct 15 '16 at 18:02

0 Answers0