3

I cannot understand how to get blobs from XMLHttpRequest in my PHP script. I have such code in JS:

var req = new XMLHttpRequest();          // create instance

var file = document.getElementById('file').files[0];     // get File Object from <input type=file />. It is picture

req.open("POST", “uploader.php”, true); // make request

req.setRequestHeader("Content-Type", file.type);   set request headers
req.setRequestHeader("Content-Length", file.size);

req.send(file);                 // send request with file-blob

if (req.readyState == 4 && req.status == 200) {
      alert("result = " + req.responseText);
}

I understand how to send the blob to the server, but don’t understand how and from where to get it there. I tried to use $_POST, $_GET and $_FILES global arrays but they don’t have any files. I even tried to add file to the url like this:

req.open("POST", “uploader.php?file=” + file, true); 

It’s not the solution either.

Reading answers here I found that I can get raw binary data using php://input. I tried and yes I got some raw data. Going to examine this solution through and through. But want to ask is this the only way? If not, what are the others? And which one is the most right then?

Also, when I set header ("Content-Length", file.size) the console.log shows error and says “Refused to set unsafe header “Content-Length”. Isn't this header necessary?

2 Answers 2

1

Check out the post below:

image upload with ajax and php

You can't really upload a blob via the XmlHttpRequest, but you can create an AJAX like feel with hidden iframes.

It looks like there are some JQuery plugins that may help you out as well.

I hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

1

Try using this for your header:

req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.