Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax JS/PHP Image Uploader not working

I tried multiple approaches and followed quite a lot questions in StkOvfl, and W3 Specifications, but still no idea.

I have a form input:

<input type="file" multiple accept="image/*" id="item-image-upload" >

Then in my Javascript (prepareFormData method): [See full gist class here]:

    var files = this.getFiles();
    var formData = new FormData();

    for (var i = 0; i < files.length; i++) {

        var file = files[i];

        if (!file.type.match('image.*')) {
            continue;
        }

        formData.append(this.uploadEntityName, file);
    }

When I console.log(files), I get all the files all fine. But, formData is not working. I also tried adding an arbitrary item as:

    formData.append("Apple", 1);

The response I get is empty. The server does repose in php as:

public function uploadImage(){
    return json_encode(array_merge($_REQUEST, $_FILES));
}
like image 742
tika Avatar asked Feb 09 '16 03:02

tika


People also ask

How to update image using AJAX in PHP?

php'; if($_POST) { $id_user= $_POST['id_user']; $img = $_FILES['image']['name']; $tmp = $_FILES['image']['tmp_name']; $valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp'); // valid extensions $path = '../images/ava/'; // upload directory try { // get uploaded file's extension $ext = strtolower(pathinfo($img, ...


1 Answers

I'm 99% sure now that it's your header, and that if you look in your logs, or turn on PHP Warnings you'll see Warning: Missing boundary in multipart/form-data POST data in Unknown on line 0

I copied this (and added your header line and removed the input file) from MDN and ran it on a script on my dev box that is set to shout all errors and I got that error, followed by an empty array

var formData = new FormData();

formData.append("username", "Groucho");
formData.append("accountnum", 123456); // number 123456 is immediately converted to a string "123456"

// JavaScript file-like object
var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
var blob = new Blob([content], { type: "text/xml"});

formData.append("somefiles[]", blob);

var request = new XMLHttpRequest();
request.open("POST", "MYDEVBOX/testpost.php");
// remove the line below and it works
request.setRequestHeader("Content-Type", "multipart/form-data");
request.responseType = "json";
request.send(formData);

Back a few minutes later after deciding to look into why. It has to do with the boundary of the multi-part data. The XHR is automatically setting the header with matching boundary when you do xhr.send(formData) (or somewhere along the way). When you set that header, the request uses that instead, wiping out the boundary and PHP doesn't know where to split the input. Here's a quick screen cap that points it out much better.

enter image description here

like image 173
aron.duby Avatar answered Oct 03 '22 03:10

aron.duby