I have a script that is creating a blob and posting it to a PHP file. Here is my code:
HTML/Javascript:
<script type="text/javascript">
function upload() {
var data = new FormData();
data.append('user', 'person');
var oReq = new XMLHttpRequest();
oReq.open("POST", 'upload.php', true);
oReq.onload = function (oEvent) {
// Uploaded.
};
var blob = new Blob(['abc123'], {type: 'text/plain'});
oReq.send(blob);
}
</script>
<button type="button" onclick="upload()">Click Me!</button>
PHP:
<?php
var_dump($_POST);
?>
When I look at my developer console, I am not getting any $_POST data on my PHP page. I need to know how to retrieve the text file being posted to PHP script.
Any help is greatly appreciated!
The data from the blob can be read from php://input, as in
<?php
var_dump(file_get_contents('php://input'));
If however you want to send multiple pieces of data with a form data object it would be like a normal multipart/form-data post. All string would be available through $_POST and all blobs and file through $_FILES.
function upload() {
var data = new FormData();
var oReq = new XMLHttpRequest();
oReq.open("POST", 'upload.php', true);
oReq.onload = function (oEvent) {
// Uploaded.
};
var blob = new Blob(['abc123'], {type: 'text/plain'});
data.append('file', blob);
oReq.send(data);
}
Append your Blob to FormData and send it instead.
Related
I have a 'stolen' code here, which i want to change the input sector to a file in my folder on the server without uploading the file first. The problem is that I am a little bit bad in javascript to figure it out, how to change the code to do that. Thanks for any help.
<script src="jquery-2.1.4.min.js"></script>
<script lang="javascript" src="xlsx.full.min.js"></script>
<input type="file" id="input-excel" src="test.xslx"/>
<div id="wrapper">
</div>
<script>
$('#input-excel').change(function(e){
reader.readAsArrayBuffer(e.target.files[0]);
reader.onload = function(e) {
var data = new Uint8Array(reader.result);
var wb = XLSX.read(data,{type:'array'});
//var htmlstr = XLSX.write(wb,{sheet:"Kondensatoren", type:'binary',bookType:'html'});
var htmlstr = XLSX.write(wb,{sheet:"Tabelle1", type:'binary',bookType:'html'});
$('#wrapper')[0].innerHTML += htmlstr;
}
});
</script>
Your question is confusing, but here is how to use AJAX to request a file on your server without the person needing to upload the file first.
What you do with it is still up to you.
I notice it's a xslx file which isn't easily parsed like a CSV, so for your ajax request you will need to parse binary.
var oReq = new XMLHttpRequest();
oReq.open("GET", "test.xslx", true);
oReq.responseType = "arraybuffer";
oReq.onload = function(oEvent) {
var arrayBuffer = oReq.response;
// if you want to access the bytes:
var byteArray = new Uint8Array(arrayBuffer);
// ...
// create a new blob (change type to whatever)
var blob = new Blob(arrayBuffer, {type: "image/png"});
// whatever...
};
oReq.send();
Thx #Tallboy. Just for other newbies as me. The full code is.
<script src="jquery-2.1.4.min.js"></script>
<script lang="javascript" src="xlsx.full.min.js"></script>
<div id="wrapper"></div>
<script>
var oReq = new XMLHttpRequest();
oReq.open("GET", "test.xlsx", true);
oReq.responseType = "arraybuffer";
oReq.onload = function(oEvent) {
var arrayBuffer = oReq.response;
var data = new Uint8Array(arrayBuffer);
var wb = XLSX.read(data,{type:'array'});
var htmlstr = XLSX.write(wb,{sheet:"Kondensatoren", type:'binary',bookType:'html'});
$('#wrapper')[0].innerHTML += htmlstr;
};
oReq.send();
</script>
So I'm trying to use formData to send a file but can't manage to make it work properly.
fileButton.addEventListener('change', function(ev)
{
var file = fileButton.files[0];
var formData = new FormData();
formData.append('file', file);
formData.append('ajax', 'fileUpload');
var xhr = new XMLHttpRequest();
xhr.open('POST', 'index.php', true);
xhr.onload = function ()
{
...
};
xhr.send(formData);
}, false);
Index.php checks that $_POST['ajax'] == 'fileUpload' and uploads the file if so.
My code works perfectly on most files but whenever I try to upload a PSD file, my index.php receives an empty $_POST and $_FILES array. I looked up the doc but can't find anything.
Many thanks!
Hi i want to save a audio file path into database and audio file into my upload folder here is my code:-
<a class="btn btn-large btn-danger" id="ahref" target="_blank" onclick="$('#audioLayerControl')[0].save($('#ahref')[0]);"><i class="icon-fire"></i> save</a>
When i clicked on this link my audio which is recorded by me is saved in downloads folder and i can play it but i want to save it in my uploads folder i am getting blob url like this blob:http%3A//localhost%3A8383/0dd9e04b-d6db-4c8c-94b5-51cfb619f725 here is its script :-
this.save = function save(saveLink)
{
var url = this.toWave().toBlobUrlAsync("application/octet-stream");
document.getElementById("ahref").src=url;
var final=document.getElementById("ahref").download = new Date().toISOString() + '.wav';
};
Thank you please help me.
Updated After using Ajax
var blobUrl=url;
var xhr = new XMLHttpRequest;
xhr.responseType = 'blob';
xhr.onload = function() {
var recoveredBlob = xhr.response;
var reader = new FileReader;
reader.onload = function() {
var blobAsDataUrl = reader.result;
window.location = blobAsDataUrl;
};
reader.readAsDataURL(recoveredBlob);
};
//xhr.open('GET', blobUrl);
xhr.open('POST', 'upload.php', true);
xhr.send(blobUrl);
Upload.php
<?php
error_reporting(0);
if( isset($HTTP_RAW_POST_DATA))
{
echo $cad = $HTTP_RAW_POST_DATA;
}
?>
Ouput:-blob:http%3A//localhost%3A8383/5155c610-dec6-4e60-8ef7-e14a56aa73d2
and in the browser url is data:text/html;base64,YmxvYjpodHRwJTNBLy9sb2NhbGhvc3QlM0E4MzgzLzUxNTVjNjEwLWRlYzYtNGU2MC04ZWY3LWUxNGE1NmFhNzNkMg==
i'll add :
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
just before the :
xhr.open('POST', 'upload.php', true);
I am using the following snippet to send a wav file as a blob to the server which is written in PHP:
function upload(blob) {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload.php', true);
xhr.onload = function (e) {
var result = e.target.result;
};
xhr.send(blob);
}
I am confused as to how I should handle the POST data on the server.
What you're looking for is php://input:
$fp = fopen("php://input", "r");
$wav_file = stream_get_contents($fp);
Note that I'm assuming blob in your example is an actual Blob, or ArrayBuffer, or File, and not just a bunch of text whose UTF8 interpretation is also a valid WAVE file.
<input type="file" id="uploadfile" name="uploadfile" />
<input type="button" value="upload" onclick="upload()" />
<script>
var client = new XMLHttpRequest();
function upload()
{
var file = document.getElementById("uploadfile");
/* Create a FormData instance */
var formData = new FormData();
/* Add the file */
formData.append("upload", file.files[0]);
client.open("post", "/upload", true);
client.setRequestHeader("Content-Type", "multipart/form-data");
client.send(formData); /* Send to server */
}
/* Check the response status */
client.onreadystatechange = function()
{
if (client.readyState == 4 && client.status == 200)
{
alert(client.statusText);
}
}
</script>
Trying to Upload some Images stored in Filesystem of Google Chrome.
But Im not able to upload the Image. Any Idea how to do it?
The Server receives an empty array. The Code of posttest.php is just print_r($_POST)
var xhr = new XMLHttpRequest();
xhr.open('POST', '/posttest.php', true);
xhr.onload = function(e) {
if (this.status == 200) {
console.log(this.responseText);
}
};
window.resolveLocalFileSystemURL(image, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
var formData = new FormData();
formData.append('image', this.result);
xhr.send(formData);
};
reader.readAsText(file);
});
});
this is the Javascript function that worked for me in chrome
function upload(filename) {
var xhr = new XMLHttpRequest();
xhr.open("post", "upload.php", true);
window.resolveLocalFileSystemURL = window.resolveLocalFileSystemURL || window.webkitResolveLocalFileSystemURL;
filename = 'filesystem:http://localhost/temporary/' + filename;
window.resolveLocalFileSystemURL(filename, function(fileEntry) {
fileEntry.file(function(file) {
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-File-Type", file.type);
xhr.send(file);
});
});
}
Now most people on the skip the upload.php taking it for granted. But it is very important and so I paste it here:
<?php
// I had to figure out what is getting passed using var_dump($_SERVER)
$fn = (isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : false);
if ($fn) {
// AJAX call
file_put_contents(
'uploads/' . $fn,
file_get_contents('php://input')
);
echo "$fn uploaded";
exit();
}
?>
Hope this helps someone, I wasted an entire day to figure this out !
First of all, your comment isn't exactly correct, the PHP code shouldn't even be receiving a blob. It's just receiving text, because you read the file as text, while png images (and almost all image types) aren't supposed to be text, they're supposed to be binary. And Blobs themselves are perfect for storing binary data, so you don't even need to use a FileReader, you can just send the Blob itself through XMLHttpRequest!
Here is how the revised fileEntry.file callback function should look:
fileEntry.file(function(file) {
xhr.send(file);
});
It's that simple! No need to read the Blob. However, you need to do some more stuff on the
PHP side now. This code will write the contents of the uploaded image to disk, then create an <img> element that allows you to view it. Here's how the PHP /posttest.php should look for that:
<?php
$rhand=fopen('php://input','r');
$cont=fread($rhand,filesize('php://input'));
fclose($rhand);
$whand=fopen('./uploaded.png','w');
fwrite($whand,$cont);
fclose($whand);
?>
<img src="uploaded.png">
It should be pretty clear what that does if you know that php://input is where php will get input from a post request if it doesn't have a MIME type that allows it to easily put it into $_POST (For example, when you have have a request with MIME type application/x-www-form-urlencoded, PHP recognizes it and is able to parse the POST contents into $_POST, but with a Blob, it doesn't, so it just outputs it out of php://input)
Please note that none of this is tested, please put a comment if it doesn't work and I'll try to fix it!
Having encountered the same challenge myself, I was able to come up with a very sleek solution. The key is to create a new Blob, from the file object returned by the fileEntry.
window.resolveLocalFileSystemURL = window.resolveLocalFileSystemURL || window.webkitResolveLocalFileSystemURL;
window.resolveLocalFileSystemURL(image, function (fileEntry) {
fileEntry.file(function (file) {
var formData = new FormData();
var tempBlob=new Blob([this.result], {type:this.result.type});
formData.append('image', tempBlob);
});
});