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!
Related
I want to be able to paste an image taken via the print screen button in a textarea and upload it to my server.
I am using onpaste and it seems to work, I can get a hold of a file object but whenever I try to send it it's empty.
onpaste(event) {
if (event.clipboardData.files.length) {
let file = event.clipboardData.files[0];
var oReq = new XMLHttpRequest();
var data = new FormData();
data.append("file", file);
data.append("csrf", CSRF_TOKEN);
oReq.open("POST", exports.url("/file"));
oReq.setRequestHeader("Accept", "application/json");
oReq.send(data);
}
}
I observe the network tab in my dev tools and a request is properly being sent with all of the information about the file except there is no contents
Request payload:
------WebKitFormBoundaryWggS2BbKcZV6v4tn
Content-Disposition: form-data; name="file"; filename="image.png"
Content-Type: image/png
------WebKitFormBoundaryWggS2BbKcZV6v4tn
Content-Disposition: form-data; name="csrf"
58718518696317230756900774635415
------WebKitFormBoundaryWggS2BbKcZV6v4tn--
In this case the file you access via event.clipboardData.files[0]; is really just a handle to the file, it doesn't contain the actual file data. To access this you must use a FileReader per the FileAPI documentation.
There are four different ways to read this data through the FileReader:
void readAsArrayBuffer(Blob blob);
void readAsBinaryString(Blob blob);
void readAsText(Blob blob, optional DOMString label);
void readAsDataURL(Blob blob);
See below an example which you can modify to fit your needs.
function onPaste(event) {
if (event.clipboardData.files.length) {
let file = event.clipboardData.files[0];
var oReq = new XMLHttpRequest();
var data = new FormData();
data.append("csrf", "TOKEN");
oReq.open("POST", "/file");
oReq.setRequestHeader("Accept", "application/json");
/* Create a new FileReader. */
var fileReader = new FileReader();
fileReader.onload = function(event) {
/* Once the file has finished loading, run the following: */
data.append("file", this.result);
oReq.send(data);
};
/* Tell the file reader to asynchronously load the files contents. */
fileReader.readAsDataURL(file);
}
}
<textarea onpaste="onPaste(event)" ></textarea>
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 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.
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);
});
});
I try to use xhr2 to upload files .
its work fine in FF , chrome but when I try it on IE10 its send only Text files no image no rar.
my script code
$("#uploader").click(function () {
alert("upload");
var fileInput = document.getElementById("fileUploader");
var file = fileInput.files[0];
var fd = new FormData();
fd.append("files", file);
alert(file.size);
var xhr = new XMLHttpRequest();
xhr.open("POST", 'http://localhost:7128/FileManager/uplader.ashx');
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-File-Type", file.type);
xhr.send(fd);
});