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
Related
I have an existing API that only accepts JSON values via a POST, it responds with a downloadable zip file that is only session based, not on a server. I wanted to create an HTML form that could be filled out and POST the JSON values to the API then receive the download. Once the API receives the JSON it will respond with a Zip file that should be downloaded through the browser. I spent a lot of time searching for how to do this and eventually pulled together the components to make it happen. I wanted to share it here because I saw many other people searching for the same thing but with no clear answers or script that worked, lost of GET examples but no POST with in memory server data. In fact may folks said it just couldn't be done with POST.
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (event) {
//Function montiors for the form submit event
event.preventDefault(); // Prevents the default action of the form submit button
var jsonData = '{"PONumber":"' + form1.PONumber.value //JSON data being submitted to the API from the HTML form
+ '","CompanyName":"' + form1.CompanyName.value
+ '","CompanyID":"' + form1.CompanyID.value
+ '","ProductName":"' + form1.ProductName.value
+ '","Quantity":"' + form1.quantity.value
+ '","Manufacturer":"' + form1.Manufacturer.value + '"}';
var xhr = new XMLHttpRequest();
xhr.open('POST', 'api_page.php', true); //The POST to the API page where the JSON will be submitted
xhr.responseType = 'blob';
xhr.setRequestHeader('Content-type', 'application/json'); //Additional header fields as necessary
xhr.setRequestHeader('Authorization', 'Bearer ' + 'eyJ0eXAiOiJKV1QiLCJhbGciO----< SNIP >---547OWZr9ZMEvZBiQpVvU0K0U');
xhr.onload = function(e) {
if (this.status == 200) {
var blob = new Blob([this.response], {type: 'application/zip'}); //We're downloading a Zip file
var downloadUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = downloadUrl;
a.download = "download_file.zip"; //The name for the downloaded file that will be saved
document.body.appendChild(a);
a.click(); //Automatically starts the download
} else {
alert('Unable to download file.')
}
};
xhr.send(jsonData); //Sends the JSON data to the destination POST page
});
});
</script>
<form method="post" name="form1" id="form1" action="" >
<td><center><input name="submit" type="submit" value="submit"></center></td>
<td ><strong>ENTER QUANTITY OF UNITS: </strong></td><td> </td>
<td><input name="quantity" type="text" size="17" value="<?php echo $row['value'];?>"></td>
</form>
Here is the code for the PHP server side of the application. The first part is to receive the request.
//Receive the incoming JSON data from the form POST
$jsonRequest = trim(file_get_contents("php://input"));
//Attempt to decode the incoming RAW post data.
$requestDecoded = json_decode($jsonRequest, true);
//Do something with the data and then respond with a zip file.
Here is the PHP code that sends the Zip file back to the original requesting page for download.
$fp = fopen('php://output', 'w'); //Creates output buffer
$mfiles = $yourZipFile
if($fp && $mfiles) {
header("Cache-Control: no-cache");
header("Content-Type: application/zip");
header("Content-Disposition: attachment;
filename=\"".basename($zipName)."\";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " .strlen($mfiles));
header("Response-Data: ".$responseData);
ob_end_clean();
if (fputs($fp, $mfiles, strlen($mfiles))===FALSE){
throw new Exception($e);
}
}
else {
throw new Exception($e);
}
Place the javascript code in the body of your HTML page and it should work just fine. I hope this helps someone else out there in the same position. I've tried to describe each component as best I can and include all of the pieces to make it work.
Request: Browser --> HTML form --> JSON --> POST --> PHP
Response: PHP --> zip file --> Browser Download --> Local PC
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 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.
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?