I am really confused in using xmlhttprequest. I want to send a file to server. Is it necessary to use formdata to send the file. I am trying to send directly using xmlhttprequest. Instead of getting a file, I am getting only a text at server side.
var Stu_Image = localStorage.getItem('StuImage');
alert(Stu_Image);
nImageRequest[i] = new XMLHttpRequest();
nImageRequest[i].open("POST", "http://10.xxx.xx.xx/server/api/upload_image.php", true);
// var ImageFile = new Image();
ImageFile = "image="+Stu_Image;
nImageRequest[i].setRequestHeader("Content-type", "application/x-www-form-urlencoded");
alert(ImageFile);
nImageRequest[i].onreadystatechange = function (oEvent)
{
if (nImageRequest[i].readyState == 4)
{
alert("4 status:"+ nImageRequest[i].status+"-------"+ nImageRequest[i].statusText);
if (nImageRequest[i].status == 200)
{
alert(nImageRequest[i].responseText);
return;
}
else
{
alert("Error:"+ nImageRequest[i].statusText);
}
}
else
{
alert("Error:"+ nImageRequest[i].readyState +"----"+nImageRequest[i].statusText);
}
};
nImageRequest[i].send(ImageFile);
This is my php file
header("Access-Control-Allow-Origin: *");
$data = $_POST['image'];
//$data = $_FILES['image']['name'];
echo "".$data;
$fileData = base64_decode($data);
echo ".....".$fileData;
$uploads_dir = "server/api/uploads/";
move_uploaded_file($fileData, $uploads_dir);
if(!file_exists($fileData) || !is_uploaded_file($fileData))
{
//echo "";
echo "No upload";
}
else
{
echo "uploaded";
}
This is how I got Stu_Image
function loadImage(Value)
{
var reader = new FileReader();
reader.readAsDataURL(document.getElementById("LoadImage").files[0]);
ImgFile = document.getElementById("LoadImage").files[0];
/
// alert(ImgFile);
localStorage.setItem('StuImage',ImgFile);
alert(ImgFile);
// alert(url);
reader.onload = function (Event)
{
document.getElementById("PreviewImage").src = Event.target.result;
};
};
Okay, so after wasting a few days, I got the answer to this question. I hope the answer helps someone if he/she gets stuck here.I am not posting the code as it is very big. I was not encoding the image before sending to server.
So the right method is
1 Store Image on Canvas.
2 Encode it using canvas.toDataURL method and send using xmlhttprequest.
3 Decode it as server side. I used php function base64_decode to do it.
4 Use imagecreatefromstring() method to convert decoded string to image and then use imagejpeg() or imagepng() method to get the image.
Hope it helps someone. Happy to post code if required by anyone.
Related
I am attempting to add an "Upload Image" feature to my AjaxChat window. The upload to the server works great, but now I need to be able to return the tmp_name/location of the file that was uploaded. In my Javascript I have the following (main) code (some setup code has been omitted because it is unnecessary -- The upload works as expected):
// Set up request
var xhr = new XMLHttpRequest();
// Open connection
xhr.open('POST', 'sites/all/modules/ajaxchat/upload.php', true);
// Set up handler for when request finishes
xhr.onload = function () {
if (xhr.status === 200) {
//File(s) uploaded
uploadButton.innerHTML = 'Upload';
} else {
alert('An error occurred!');
}
};
// Send data
xhr.send(formData);
My PHP code ("upload.php") is as follows:
<?php
$valid_file = true;
echo '<script type="text/javascript">alert("PHP Code Reached");</script>';
if($_FILES['photo']['name']) {
//if no errors...
if(!$_FILES['photo']['error']) {
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
if($_FILES['photo']['size'] > (1024000)) { //can't be larger than 1 MB
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
exit("$message");
}
//if the file has passed the test
if($valid_file) {
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], '/var/www/html/images'.$new_file_name);
$message = 'Congratulations! Your file was accepted.';
exit("$message");
}
}
//if there is an error...
else {
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error'];
exit("$message");
}
}
?>
I can tell my PHP code is being run because the image uploads to the server. However, I read that I could generate a Javascript "alert" popup from within the PHP using the following code:
echo '<script type="text/javascript">alert("PHP Code Reached");</script>';
But the above line does not seem to be doing anything. Is this expected since I'm using an XMLHttpRequest, rather than running the PHP directly?
Ultimately my goal is to pass the name of the uploaded file back to the Javascript that called the PHP so that I can create the image url, put it in img tags, and send it to the chat window using ajaxChat.insertText() and ajaxChat.sendMessage(). I'm not sure if this is possible the way I'm running my PHP, though. How would one go about doing this?
When you use XMLHttpRequest, the output of the server script is in the responseText of the object. So you can do:
xhr.onload = function () {
if (xhr.status === 200) {
//File(s) uploaded
uploadButton.innerHTML = xhr.responseText;
} else {
alert('An error occurred!');
}
};
If you want to send back multiple pieces of information, such as an informative message and the name of the file, you can use JSON to encode an associative array, which will become a Javascript object when you parse it.
I have an image created with a JavaScript Blob which I need to upload to a PHP script.
My JavaScript upload function...
function upload(blobOrFile) {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://requestb.in/17m14c51', true);
xhr.onload = function(e) {
//
};
// Listen to the upload progress.
//var progressBar = document.querySelector('progress');
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
console.log((e.loaded / e.total) * 100);
//progressBar.textContent = progressBar.value; // Fallback for unsupported browsers.
}
};
xhr.send(blobOrFile);
}
This URL http://requestb.in/17m14c51?inspect shows the data that this code is posting.
My Image is coming in as an image. I am not sure how to access this image in my PHP script though as I do not see any form or file name, maybe I am missing it?
Previously my PHP had the image come in as Base64 so this PHP below did the upload...
function base64_to_jpeg($base64_string, $output_file) {
//$output_file_new= $output_file.'-'.md5(time().uniqid()).'.jpg';
$output_file_new= $output_file;
$ifp = fopen($output_file_new, "wb");
$base64_string2 = urldecode($base64_string);
$data = explode(',', $base64_string2);
$decoded = base64_decode($data[1]);
fwrite($ifp, $decoded);
fclose($ifp);
echo json_encode(array('img_url' => $output_file_new, 'headers' => parseRequestHeaders()));
//return $output_file_new;
}
Now that I am not getting it as Base64, how can I save it in my PHP?
I am relatively new to php and I am trying to make use of the move_uploaded_file() function.
I firstly send a HTTP POST request from some javascript/jquery to a php file as follows with an audio blob....my php file is hosted on a microsoft azure server...
mediaRecorder.ondataavailable = function(e) {
var fileType = 'audio';
var fileName = 'test.ogg';
var formData = new FormData();
formData.append(fileType + '-filename', fileName);
formData.append(fileType + '-blob', e.data);
// e.data is the audio blob
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
console.log('wooo');
}
};
request.open('POST', myserver/Test.php');
request.send(formData);
}
My PHP code picks up this post request and seems to receive the file with no errors
<?php
print_r($_FILES);
$temp = $_FILES['audio-blob']['tmp_name'];
$name = $_FILES['audio-blob']['name'];
if (isset($_FILES["audio-blob"])) {
$fileName = $_POST["audio-filename"];
$uploadDirectory = 'C:/Users/Liam/PhpRecordings/';
if (move_uploaded_file($temp, $uploadDirectory . $fileName)) {
echo("file moved!!!!");
}
else
{
echo(" problem moving uploaded file");
}
}
?>
<html>
<body>
Test
</body>
</html>
<?
?>
However, when trying to move the file it does not succeed and I get the echo
problem moving uploaded file
The full post response is here
Array (
[audio-blob] => Array
(
[name] => blob
[type] => audio/ogg
[tmp_name] => D:\local\Temp\phpA897.tmp
[error] => 0
[size] => 15755
)
) problem moving uploaded file Test
Does anybody know why the file move is not occurring?
Thanks
Is there are enough rights for your code to write to /Users/Liam/PhpRecordings/?.
Try to run this code and add output into comment for this answer:
echo file_put_contents('/Users/Liam/PhpRecordings/test.txt', 'testing_writing_to_file');
According to the author's further comments there are problems with write privileges to $uploadDirectory.
There are similar question on SO - Write permissions on mac
I am trying to saeve recorded file to the server.
For recording purpose I am using demos recorder
At the end of recording it gives me a blob-link to the recorded file.
So After googling a bit I found that I can use that bob url to save it.
Here is the link that talks about saving blobs.
After that I am trynig to get it and download to server.
1- I get the link to blob file
var data = document.getElementById("save").href
After that
I am using js code in my index.html file to send
blob url to php code.
JS code
<script>
function saveAudio(){
var req = null;
var url = "savefile.php";
var data = document.getElementById("save").href.toString();// document.getElementById("save").innerHTML;// = xhttp.responseText;; // you have to check how to get the data from your saveAudio() method
window.alert(data);
(window.XMLHttpRequest) ? req = new XMLHttpRequest() : (window.ActiveXObject) ? req = new ActiveXObject("Microsoft.XMLHTTP") : req = false;
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "multipart/form-data");
if(data != null) //&& data != "")
{
req.setRequestHeader("Content-length", data.length);
req.send(data);
}}
</script>
PHP code
<?php
$save_folder = dirname(__FILE__) ."/js";
if(! file_exists($save_folder)) {
if(! mkdir($save_folder)) {
die("failed to create save folder $save_folder");
}
}
$key = 'filename';
$tmp_name = $_FILES["audiofile"]["tmp_name"];
$upload_name = $_FILES["audiofile"]["name"];
$type = $_FILES["audiofile"]["type"];
$filename = "$save_folder/$upload_name";
$saved = 0;
if(($type == 'audio/x-wav' || $type == 'application/octet-stream') && preg_match('/^[a-zA-Z0-9_\-]+\.wav$/', $upload_name) ) {
$saved = move_uploaded_file($tmp_name, $filename) ? 1 : 0;
}
//name is needed to send in the php file
?>
I get 2 errors while compiling in browser
1-refused to set unsafe header "Content-length".
2-POST savefile.php 500
I suppose that there is something wrong with php file!
How canI handle these errors and accomplish uploading task?
Is there any open source which allows direct uploading blob-url to server without using php?
I appreciate any help and suggestion!
Try removing the line:
req.setRequestHeader("Content-length", data.length);
XMLHttpRequest isn't allowed to set these headers because that would be a security vulnerability. The 500 is most likely a result of the request failure.
You can read about XMLHttpReqest here http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method
Here are some other threads, same issue:
Pass Blob through ajax to generate a file
How can javascript upload a blob?
From System.Shell.itemFromFileDrop I get System.Shell.Item object item. I've tried this:
var oStream = new ActiveXObject("ADODB.Stream");
oStream.Type = 1;
oStream.Open();
oStream.LoadFromFile(item.path);
content = oStream.Read();
var thisObj = this;
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://myUrl.com//");
xhr.send(content); //NOT WORKING
oStream.Close();
oStream = null;
but I really don't know what to pass in the xhr.send function.
The serverside PHP code is as simple as it could be:
if (file_exists($_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],$_FILES["file"]["name"]);
header("{$_SERVER['SERVER_PROTOCOL']} 200 OK");
header('Content-Type: text/plain');
echo "http://myUrl.com/" .$_FILES["file"]["name"];
}
any ideas what am I doing wrong ? Or any ideas about how to upload files from windows gadget at all?