I have tried using some code to get blob uploaded to server, but this code has not functioned as intended. need help in finding where the error is and perhaps how to upload blob video to MySQL server.
The js code I used is
var blob = URL.createObjectURL(recorder.getBlob());
var fd = new FormData();
fd.append('fname', 'test.mp4');
fd.append('data', blob);
$.ajax({
type: 'POST',
url: '../../application/controllers/upload.php',
data: fd,
processData: false,
contentType: false
}).done(function(data) {
alert(data);
});
Then this is the PHP code I tried
foreach(array('video', 'audio') as $type) {
if (isset($_FILES["${type}-blob"])) {
echo 'uploads/';
$fileName = $_POST["${type}-filename"];
$uploadDirectory = 'uploads/'.$fileName;
if (!move_uploaded_file($_FILES["${type}-blob"]["tmp_name"], $uploadDirectory)) {
echo(" problem moving uploaded file");
}
echo($fileName);
}
}
Once I am able to get this working I can be able to insert the data into MySQL database
Thank you for helping
you placed your blob into your formdata OBJECT and called it data
fd.append('data', blob);
So when that gets to PHP is will be placed in
$_FILES['data']
Just like as if you had done
<input type="file" name="data">
Related
trying to upload a file without using a form and using $.post to transfer the file
I suppose the problem is on php side, but I'm not sure
<input type='file' id='inpfile'>
$(inpfile).on('change', function(){
var fd = new FormData();
var file = $(inpfile)[0].files[0];
fd.append('file', file);
fd = JSON.stringify(fd);
$.post('pro.php', {fn: 'upload', args: [fd]}, function(data){
console.log(data);
});
});
pro.php
if(isset($_POST['fn'], $_POST['args'])){
$fn = $_POST['fn']; $args = $_POST['args'];
$fn(...$args);
}
function upload($fd){
$fd = json_decode($fd);
$fname = $fd->file;
$destination = 'upload/' . $fname;
move_uploaded_file($fname, $destination);
}
you cannot upload file simply with $.post method and form data when changed to string cannot send file. you need to add contentType:false and processData:false, and remove this code fd = JSON.stringify(fd); Moreover, your jquery does not recognize the change since you have not addressed it properly. it should be $('#inpfile').on('change', function()
instead of just $(inpfile).on('change', function()
you can try this code.
<input type='file' id='inpfile'>
$('#inpfile').on('change', function(){
var fd = new FormData();
var files = $('#inpfile')[0].files;
fd.append('file',files[0]);
$.ajax({
url: 'pro.php',
method: 'post',
data: fd,
contentType: false,
processData: false,
success: function(response){
//your code.....
}
});
});
and in the PHP server side you check it with files method instead of post method. that is
if(isset($_FILES['file']['fd'])){
your code.......
}
I'm using javascript to get the filepath but it returns C:\fakepat\ fileName, then I replace the fakepath to get the filename only. Then ajax to php. And execute this line:
copy("filename", $targetPath);
It returns this error no directory or file.
PHP is executed on server-side, therefor it has no access to your client-side file.
To transmit the file from client to server using ajax I recommend wrapping a form around your upload-button. After submitting the XHR you can access the file in PHP via the $_FILES variable and move it where ever you want:
HTML
<form>
<input type="file" id="upload" onchange="javascript:uploadFile()" />
</form>
JS
function uploadFile() {
var formData = new FormData(); // using XMLHttpRequest2
var fileInput = document.getElementById('upload');
var file = fileInput.files[0];
formData.append("uploadfile", file);
request.send(formData);
}
PHP
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['uploadfile']['name']);
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $uploadfile)) {
// upload succeeded
} else {
// upload failed
}
in ajax you can write this
var form_data = new FormData();
var file_data1 = $('#file').prop('files')[0];
form_data.append('file', file_data1);
$.ajax({
url: 'assets/addEdi.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (php_script_response) {
$('#res').html(php_script_response);
}
});
#Toltis Because of the fakepath, you should upload via javascript.
This it the html:
<input type="file" id="file" onchange="upload(event)" />
<img src="" id="img" />
<textbox id="hidden_box" name="hidden_box" style="visibility: hidden;"></textbox>
Then the Js:
function upload(e) {
var input_file = document.getElementById('file');
var hidden = document.getElementById('hidden_box');
var fr = new FileReader();
fr.readAsDataURL(input_file.files[0]);
fr.onloadend = function(e) {
var img_tag = document.getElementById('img');
dataUrl = e.target.result;
img_tag = dataUrl
hidden.innerHTML = dataUrl
}
}
Then you can target the contents of the hidden box in php. Break it on the (,) and then decode the remaining string - base64_decode - and then save it to a file.
The real file name, you already know how to get it.
I want to implement a simple file upload in my intranet-page, with the smallest setup possible.
This is my HTML part:
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload">Upload</button>
and this is my JS jquery script:
$("#upload").on("click", function() {
var file_data = $("#sortpicture").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data);
alert(form_data);
$.ajax({
url: "/uploads",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(){
alert("works");
}
});
});
There is a folder named "uploads" in the root directory of the website, with change permissions for "users" and "IIS_users".
When I select a file with the file-form and press the upload button, the first alert returns "[object FormData]". the second alert doesn't get called and the"uploads" folder is empty too!?
Can someone help my finding out whats wrong?
Also the next step should be, to rename the file with a server side generated name. Maybe someone can give me a solution for this, too.
You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running on the client in the browser) sends the form data to the server, then a script running on the server handles the upload.
Your HTML is fine, but update your JS jQuery script to look like this:
(Look for comments after // <-- )
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // <-- point to server-side PHP script
dataType: 'text', // <-- what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // <-- display response from the PHP script, if any
}
});
});
And now for the server-side script, using PHP in this case.
upload.php: a PHP script that is located and runs on the server, and directs the file to the uploads directory:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
Also, a couple things about the destination directory:
Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
Make sure it's writeable.
And a little bit about the PHP function move_uploaded_file, used in the upload.php script:
move_uploaded_file(
// this is where the file is temporarily stored on the server when uploaded
// do not change this
$_FILES['file']['tmp_name'],
// this is where you want to put the file and what you want to name it
// in this case we are putting in a directory called "uploads"
// and giving it the original filename
'uploads/' . $_FILES['file']['name']
);
$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:
move_uploaded_file(
$_FILES['file']['tmp_name'],
'uploads/my_new_filename.whatever'
);
And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.
**1. index.php**
<body>
<span id="msg" style="color:red"></span><br/>
<input type="file" id="photo"><br/>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','#photo',function(){
var property = document.getElementById('photo').files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
alert("Invalid image file");
}
var form_data = new FormData();
form_data.append("file",property);
$.ajax({
url:'upload.php',
method:'POST',
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function(){
$('#msg').html('Loading......');
},
success:function(data){
console.log(data);
$('#msg').html(data);
}
});
});
});
</script>
</body>
**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
$test = explode('.', $_FILES['file']['name']);
$extension = end($test);
$name = rand(100,999).'.'.$extension;
$location = 'uploads/'.$name;
move_uploaded_file($_FILES['file']['tmp_name'], $location);
echo '<img src="'.$location.'" height="100" width="100" />';
}
Use pure js
async function saveFile()
{
let formData = new FormData();
formData.append("file", sortpicture.files[0]);
await fetch('/uploads', {method: "POST", body: formData});
alert('works');
}
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload" onclick="saveFile()">Upload</button>
<br>Before click upload look on chrome>console>network (in this snipped we will see 404)
The filename is automatically included to request and server can read it, the 'content-type' is automatically set to 'multipart/form-data'. Here is more developed example with error handling and additional json sending
async function saveFile(inp)
{
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = inp.files[0];
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
try {
let r = await fetch('/upload/image', {method: "POST", body: formData});
console.log('HTTP response code:',r.status);
alert('success');
} catch(e) {
console.log('Huston we have problem...:', e);
}
}
<input type="file" onchange="saveFile(this)" >
<br><br>
Before selecting the file Open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
var formData = new FormData($("#YOUR_FORM_ID")[0]);
$.ajax({
url: "upload.php",
type: "POST",
data : formData,
processData: false,
contentType: false,
beforeSend: function() {
},
success: function(data){
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
and this is the php file to receive the uplaoded files
<?
$data = array();
//check with your logic
if (isset($_FILES)) {
$error = false;
$files = array();
$uploaddir = $target_dir;
foreach ($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
$files[] = $uploaddir . $file['name'];
} else {
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
} else {
$data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);
}
echo json_encode($data);
?>
I'm using pdfmake to create my pdf and while it allows the user to open the pdf directly or download it to their computer, I'm not sure how I would go about generating the pdf and saving it to my server's file system.
From what I understand, there are plenty of security measures not allowing javascript to save data to file(s), so would sending it to my php backend be the only choice ? and how would i go about doing that ?
Thanks !
(untested)
PHP:
<?
// pull the raw binary data from the POST array
$data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
// decode it
$decodedData = base64_decode($data);
// print out the raw data,
echo ($decodedData);
$filename = "test.pdf";
// write the data out to the file
$fp = fopen($filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>
JS:
var docDefinition = {
content: 'This is an sample PDF printed with pdfMake'
};
pdfMake.createPdf(docDefinition).getBuffer(function(buffer) {
var blob = new Blob([buffer]);
var reader = new FileReader();
// this function is triggered once a call to readAsDataURL returns
reader.onload = function(event) {
var fd = new FormData();
fd.append('fname', 'test.pdf');
fd.append('data', event.target.result);
$.ajax({
type: 'POST',
url: 'upload.php', // Change to PHP filename
data: fd,
processData: false,
contentType: false
}).done(function(data) {
// print the output from the upload.php script
console.log(data);
});
};
// trigger the read from the reader...
reader.readAsDataURL(blob);
});
Upload and receive code from How can javascript upload a blob?.
I'm using an audio recorder from this place
http://webaudiodemos.appspot.com/AudioRecorder/index.html,
but I instead of saving the file locally I would like to upload it back to the server. My best shot was to try to modify the Recorder.setupDownload function in recording.js script to pass the blob it creates to a simple upload PHP script I found here:
<?php
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['recording']['name'];
$file_size =$_FILES['recording']['size'];
$file_tmp =$_FILES['recording']['tmp_name'];
$file_type=$_FILES['recording']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$extensions = array("wav");
if(in_array($file_ext,$extensions )=== false){
$errors[]="extension not allowed, please choose wav file."
}
if($file_size > 2097152){
$errors[]='File size under 20MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
?>
And I'm tring it using a jquery call,
$.ajax({
type: "POST",
url: "../scripts/Single-File-Upload-With-PHP.php",
data: blob
});
But I'm obviously doing something wrong. The original PHP script has a form in it
used for input, which I commented out trying to call the php code directly.
So my questions would be;
how to modify the Recorder.setupDownload to upload the file to a
designated folder?
how to report back when something goes wrong?
Or alternatively, is there a more elegant solution?
Edit: Regarding what's in the blob
This is how the blob is being defined in recorder.js:
worker.onmessage = function(e){
var blob = e.data;
currCallback(blob);
}
As to my understanding it is created with methods listed in recorderWorker.js (link in comments), and it should contain simply a wav file.
I dont think you should create the blob in the worker, but I had a similar setup (actually based on the same example) where I retrieved the samplebuffers from the worker and save them into the m_data fields of an AudioMixer class that did some stuff to the recording, then:
//! create a wav file as blob
WTS.AudioMixer.prototype.createAudioBlob = function( compress ){
// the m_data fields are simple arrays with the sampledata
var dataview = WTS.AudioMixer.createDataView( this.m_data[ 0 ], this.m_data[ 1 ], this.m_sampleRate );
return( new Blob( [ dataview ], { type:'audio/wav' } ) );
}
WTS.AudioMixer.createDataView = function( buffer1, buffer2, sampleRate ){
var interleaved = WTS.AudioMixer.interleave( buffer1, buffer2 );
// here I create a Wav from the samplebuffers and return a dataview on it
// the encodeWAV is not provided..
return( WTS.AudioMixer.encodeWAV( interleaved, false, sampleRate ) );
}
then to send it to the server
var blob = this.m_projectView.getAudioEditView().getAudioMixer().createAudioBlob();
if( blob ){
//! create formdata (as we don't have an input in a DOM form)
var fd = new FormData();
fd.append( 'data', blob );
//! and post the whole thing #TODO open progress bar
$.ajax({
type: 'POST',
url: WTS.getBaseURI() + 'mixMovie',
data: fd,
processData: false,
contentType: false
} );
}
and I had a node server running where the blob was sent to and could be picked up directly as a wav file, using the express node module:
var express = require( 'express' );
// we use express as app framework
var app = express();
/** mixMovie expects a post with the following parameters:
* #param 'data' the wav file to mux together with the movie
*/
app.post( '/mixMovie', function( request, response ){
var audioFile = request.files.data.path;
....
} );
hope this helps..
Jonathan
In the end this worked nicely for me:
recorder.js:
$.ajax(
{
url: "./scripts/upload.php?id=" + Math.random(),
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(data){
alert('Your message has been saved. \n Thank you :-)');
}
});
And the upload script itself:
<?php
if(isset($_FILES['data']))
{
echo $_FILES['data']["size"];
echo $_FILES['data']["type"];
echo $_FILES['data']["tmp_name"];
$name = date(YmdHis) . '.wav';
move_uploaded_file($_FILES['data']["tmp_name"],"../DEST_FOLDER/" . $name);
}
?>