Upload getUserMedia blob with Perl - perl

I have problem with upload video file - blob, to our server. I tried solve this by javascript, but I have response 403.
So I tried do it with perl, but nothing happend. I know, that when I try create and save empty txt file with perl, it works (it is upload on server). So I hoped, that it will be similar. But it doesn´t work :(
I´m very basic programmer, please apologize me.
Please, how can I save the file to the server?
Thank you very much.
<html>
<div class="left">
<div id="startButton" class="button">
Start
</div>
<h2>Preview</h2>
<video id="preview" width="160" height="120" autoplay muted></video>
</div>
<div class="right">
<div id="stopButton" class="button">
Stop
</div>
<h2>Recording</h2>
<video id="recording" width="160" height="120" controls></video>
<a id="downloadButton" class="button">
Download
</a>
<a id="uploadButton" class="button" action="upload_ML_v01.pl" method="post" enctype="multipart/form-data">
Upload
</a>
</div>
<script>
let preview = document.getElementById("preview");
let recording = document.getElementById("recording");
let startButton = document.getElementById("startButton");
let stopButton = document.getElementById("stopButton");
let downloadButton = document.getElementById("downloadButton");
let logElement = document.getElementById("log");
let uploadButton = document.getElementById("uploadButton");
let recordingTimeMS = 5000;
function log(msg) {
//logElement.innerHTML += msg + "\n";
}
function wait(delayInMS) {
return new Promise(resolve => setTimeout(resolve, delayInMS));
}
function startRecording(stream, lengthInMS) {
let recorder = new MediaRecorder(stream);
let data = [];
recorder.ondataavailable = event => data.push(event.data);
recorder.start();
log(recorder.state + " for " + (lengthInMS/1000) + " seconds...");
let stopped = new Promise((resolve, reject) => {
recorder.onstop = resolve;
recorder.onerror = event => reject(event.name);
});
let recorded = wait(lengthInMS).then(
() => recorder.state == "recording" && recorder.stop()
);
return Promise.all([
stopped,
recorded
])
.then(() => data);
}
function stop(stream) {
stream.getTracks().forEach(track => track.stop());
}
startButton.addEventListener("click", function() {
navigator.mediaDevices.getUserMedia({
video: true,
audio: false
}).then(stream => {
preview.srcObject = stream;
downloadButton.href = stream;
preview.captureStream = preview.captureStream || preview.mozCaptureStream;
return new Promise(resolve => preview.onplaying = resolve);
}).then(() => startRecording(preview.captureStream(), recordingTimeMS))
.then (recordedChunks => {
let recordedBlob = new Blob(recordedChunks, { type: "video/webm" });
//upload it to server part start............................
var xhr = new XMLHttpRequest();
var fd = new FormData();
fd.append("video",recordedBlob);
xhr.open('POST', 'video', recordedBlob)
xhr.send(fd);
recording.src = URL.createObjectURL(recordedBlob);
downloadButton.href = recording.src;
downloadButton.download = "RecordedVideo.webm";
log("Successfully recorded " + recordedBlob.size + " bytes of " +
recordedBlob.type + " media.");
})
.catch(log);
}, false);
stopButton.addEventListener("click", function() {
stop(preview.srcObject);
}, false);
</script>
</html>
and perl file:
use strict;
use warnings;
use CGI;
use CGI::Carp qw/fatalsToBrowser/;
use File::Basename;
$|=1; # auto flush
$CGI::DISABLE_UPLOADS = 0;
my $query = CGI->new; # ..global query
my $src_filehandle = $query->upload('recording.src');
my $upld_pathfilename = "video.webm";
open (UPLOADFILE, ">",$upld_pathfilename);
my $totalbytes = 0;
while ( <$src_filehandle> ) {
print UPLOADFILE;
$totalbytes += length;
};
close UPLOADFILE

Your JavaScript code does not look right:
xhr.open('POST', 'video', recordedBlob)
The open method expects a boolean as the third argument, see documentation. You are sending it a blob instead.
Here is an example of how you can send binaray data.

Related

overlayMaps and markers in Leaflet

I am using Leaflet to show two sets of markers on a map. Let's call them "trip 1" and "trip 2".
The markers information (lat, lon, description, etc.) is stored in two separate geojson files.
I would like to show each trip separately, using two L.layerGroup, one for each trip.
The code below is the page I have written: so far this is what I have.
The problem is that all markers are already shown on the map before selecting each trip (top right corner - see attached image).
I would like the markers to be shown after selection.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<center>
<div id="map" class="embed-container"></div>
</center>
<script>
var viaggio1 = L.layerGroup([
<?php
$url = 'docs/guardini.geojson'; // path to your JSON file
$dati = file_get_contents($url); // put the contents of the file into a variable
$result = json_decode($dati, true); // decode the JSON feed
$data = $result['features'];
foreach($data as $key => $row) {
$numero = $row['id'];
$nome = $row['name'];
$lat = $row['lat'];
$lon = $row['lon'];
$text = $row['text'];
$pic = $row['pic'];
$link = $row['link'];
?>
L.marker(['<?=$lat;?>', '<?=$lon;?>']),
<?php
}
?>
]);
</script>
<script>
var viaggio2 = L.layerGroup([
<?php
$url2 = 'docs/guardini2.geojson'; // path to your JSON file
$dati2 = file_get_contents($url2); // put the contents of the file into a variable
$result2 = json_decode($dati2, true); // decode the JSON feed
$data2 = $result2['features'];
foreach($data2 as $key2 => $row2) {
$numero2 = $row2['id'];
$nome2 = $row2['name'];
$lat2 = $row2['lat'];
$lon2 = $row2['lon'];
$text2 = $row2['text'];
$pic2 = $row2['pic'];
$link2 = $row2['link'];
?>
L.marker(['<?=$lat2;?>', '<?=$lon2;?>']),
<?php
}
?>
]);
</script>
<script>
var overlayMaps = {
"viaggio 1": viaggio1,
"viaggio 2": viaggio2
};
var map = L.map('map').setView([48.3585, 10.86135], 6);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{
attribution: '© OpenStreetMap',
maxZoom: 19,
minZoom: 4
}).addTo(map);
L.control.scale({imperial: false}).addTo(map);
var pol = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{
attribution: '© OpenStreetMap',
minZoom: 4,
maxZoom: 19
}).addTo(map);
var sat = L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
{
attribution: 'Tiles © Esri — Source: Esri, IGN, IGP, UPR-EGP, and the GIS User Community',
minZoom: 4,
maxZoom: 19
});
var arte = L.tileLayer('http://stamen-tiles-{s}.a.ssl.fastly.net/watercolor/{z}/{x}/{y}.{ext}',
{
attribution: 'Map tiles by Stamen Design, CC BY 3.0 — Map data © OpenStreetMap',
subdomains: 'abcd',
minZoom: 4,
maxZoom: 19,
ext: 'png'
});
var baseMaps = {
"politica": pol,
"satellitare": sat,
"artistica": arte
};
//L.control.layers(baseMaps).addTo(map);
L.control.layers(baseMaps, overlayMaps).addTo(map);
var stile = {
"color": "#ff3385",
"weight": 4,
"opacity": 0.65
};
</script>
<?php
$url = 'docs/guardini.geojson'; // path to your JSON file
$dati = file_get_contents($url); // put the contents of the file into a variable
$result = json_decode($dati, true); // decode the JSON feed
$data = $result['features'];
foreach($data as $key => $row) {
$numero = $row['id'];
$nome = $row['name'];
$lat = $row['lat'];
$lon = $row['lon'];
$text = $row['text'];
$pic = $row['pic'];
$link = $row['link'];
?>
<div id="sidebar<?=$numero;?>" align="left"></div>
<script>
var sidebar<?=$numero;?> = L.control.sidebar('sidebar<?=$numero;?>', {
closeButton: true,
position: 'left'
});
sidebar<?=$numero;?>.setContent('<br>luogo nr. <?=$numero;?><br><br><b><?=$nome;?></b><br><br><?=$text;?><br><br><img src="<?=$pic;?>"><br><br><?=$link;?><br>');
map.addControl(sidebar<?=$numero;?>);
setTimeout(function () {
sidebar<?=$numero;?>.hide();
}, 700);
var marker<?=$numero;?> = L.marker(['<?=$lat;?>', '<?=$lon;?>']).addTo(map).on('click', function () {
sidebar<?=$numero;?>.toggle();
});
</script>
<?php
}
?>
<?php
$url2 = 'docs/guardini2.geojson'; // path to your JSON file
$dati2 = file_get_contents($url2); // put the contents of the file into a variable
$result2 = json_decode($dati2, true); // decode the JSON feed
$data2 = $result2['features'];
foreach($data2 as $key2 => $row2) {
$numero2 = $row2['id'];
$nome2 = $row2['name'];
$lat2 = $row2['lat'];
$lon2 = $row2['lon'];
$text2 = $row2['text'];
$pic2 = $row2['pic'];
$link2 = $row2['link'];
?>
<div id="sidebar<?=$numero2;?>" align="left"></div>
<script>
var sidebar<?=$numero2;?> = L.control.sidebar('sidebar<?=$numero2;?>', {
closeButton: true,
position: 'left'
});
sidebar<?=$numero2;?>.setContent('<br>luogo nr. <?=$numero2;?><br><br><b><?=$nome2;?></b><br><br><?=$text2;?><br><br><img src="<?=$pic2;?>"><br><br><?=$link2;?><br>');
map.addControl(sidebar<?=$numero2;?>);
setTimeout(function () {
sidebar<?=$numero2;?>.hide();
}, 700);
var markerr<?=$numero2;?> = L.marker(['<?=$lat2;?>', '<?=$lon2;?>']).addTo(map).on('click', function () {
sidebar<?=$numero2;?>.toggle();
});
</script>
<?php
}
?>
</div>
</div>
</body>
</html>
It looks like you are adding the markers to the map:
L.marker(['<?=$lat2;?>', '<?=$lon2;?>']).addTo(map)
And I think what you want to do is add the markers to the layerGroups:
L.marker(['<?=$lat2;?>', '<?=$lon2;?>']).addTo(viaggio2)

How to save multiple image path to database while image is saved to server

I have this code on how to save multiple images to server using codeigniter and ajax
I have gone through this code, though i'm still learning Ajax, Json and Javascript. But i want to be able to save the image paths (for all images uploaded to the database so i can be able to retrieve them for each user. Just the was facebook image upload is). The code below is in my view file.
$(document).ready(function(){
$('#profiles').change(function(){
var files = $('#profiles')[0].files;
var error = '';
var form_data = new FormData();
for(var count = 0; count<files.length; count++){
var name = files[count].name;
var extension = name.split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1){
error += " " + count + "Invalid Image File(s)"
}
else {
form_data.append("profiles[]", files[count]);
}
}
if(error == ''){
$.ajax({
url:"<?php echo base_url(); ?>pastors/upload_image",
method:"POST",
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function() {
$('#upl_images').html("<label class='text-success'>Uploading...</label>");
},
success:function(data){
$('#upl_images').html(data);
$('#profiles').val('');
document.getElementById("success_msg").style.transition="all 0.9s ease";
document.getElementById("success_msg").style.opacity=0.5;
document.getElementById("success_msg").innerHTML="Images Successfully Uploaded";
//alert(pastor +" "+ "You saved a new report");
setTimeout(remove_prodiv, 1500);
}
})
}
else{
alert(error);
}
});
});
And this is my controller
public function upload_image(){
if($_FILES["profiles"]["name"] != ''){
$output = '';
$config["upload_path"] = './programphoto/';
$config["allowed_types"] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
$this->upload->initialize($config);
for($count = 0; $count<count($_FILES["profiles"]["name"]); $count++){
$_FILES["file"]["name"] = $_FILES["profiles"]["name"][$count];
$_FILES["file"]["type"] = $_FILES["profiles"]["type"][$count];
$_FILES["file"]["tmp_name"] = $_FILES["profiles"]["tmp_name"][$count];
$_FILES["file"]["error"] = $_FILES["profiles"]["error"][$count];
$_FILES["file"]["size"] = $_FILES["profiles"]["size"][$count];
if($this->upload->do_upload('file')){
$data = $this->upload->data();
//$image=$data["file_name"];
//$this->pastors_model->SaveReport($image);
$output .= '
<div class="col-md-2">
<img src="'.base_url().'programphoto/'.$data["file_name"].'" class="img-responsive img-thumbnail" />
</div>
';
}
}
echo $output;
}
}
This code uploads images perfectly to the server. but i just want a way out to saving the paths to database
I got this working.
All I did was to send the file names to the model each time it uploads,
like this:
if($this->upload->do_upload('file')){
$data = $this->upload->data();
$output .= '
<div class="col-md-2">
<img src="'.base_url().'folder/'.$data["file_name"].'" class="img-responsive img-thumbnail" />
</div>
';
$filename = $data['file_name'];
$this->Model->save_file($filename);
}

react multiple input field with same name attribute triggers multiple updates in different inputs

So, the problem is below.
handleBankAccountInput = (e, key) => {
let name = e.target.name;
let value = e.target.value;
let validation = e.target.key;
let bankAccounts = {...this.state.bankAccounts};
let ibanValid = bankAccounts[key].validationState.iban;
let banknameValid = bankAccounts[key].validationState.bankname;
bankAccounts[key][name] = value;
switch(validation) {
case 'iban':
ibanValid = IBAN.isValid(value); // true
bankAccounts[key].fieldValidationErrors.iban = ibanValid ? '' : ' is invalid IBAN';
bankAccounts[key].validationState.iban = ibanValid ? 'success' : 'error';
console.log("why validate all iban of bankAccounts of key: " + key );
console.log(bankAccounts[key]);
break;
case 'bankname':
banknameValid = value.length >=1; // true
bankAccounts[key].fieldValidationErrors.bankname = banknameValid ? '' : ' is invalid bankname';
bankAccounts[key].validationState.bankname = banknameValid ? 'success' : 'error';
console.log("why validate all bankname of bankAccounts of key: " + key );
console.log(bankAccounts[key]);
break;
default:
break;
}
// bankAccounts[key] = bankAccount;
this.setState({bankAccounts: bankAccounts}, this.validateForm);
bankAccounts = {};
}
Problem:
The line ' bankAccounts[key].fieldValidationErrors.iban =
ibanValid ? '' : ' is invalid IBAN'; ' is triggered by other inputs
with same name attribute.
addBankAccountInput = () => {
let bankAccounts = {...this.state.bankAccounts};
// add in our new menu
let bankAccount = {...this.state.bankAccount};
bankAccount['iban'] = '';
bankAccount['bankname'] = '';
bankAccount['validationState']['iban'] = '';
bankAccount['validationState']['bankname'] = '';
bankAccount['formErrors']['iban'] = '';
bankAccount['formErrors']['bankname'] = '';
bankAccount['fieldValidationErrors']['iban'] = '';
bankAccount['fieldValidationErrors']['bankname'] = '';
let accountnum = 0;
if(bankAccounts) {
Object.keys(bankAccounts).map((key) => accountnum++ );
}
bankAccounts[accountnum] = bankAccount;
this.setState({ bankAccounts: bankAccounts });
bankAccount = {};
bankAccounts = {};
}
This is how I add empty bankAccount inputs.
renderBankAccountInput = (key) => {
return (
<div key={key}>
<FormGroup controlId={'formHorizontalBankAccount'+key} validationState={this.state.bankAccounts[key].validationState.iban}>
<Col componentClass={ControlLabel} sm={2}>
IBAN
</Col>
<Col sm={10}>
<FormControl type="text" name={'iban'+key} key='iban' value={this.state.bankAccounts[key].iban} placeholder="iban" onChange={(e) => this.handleBankAccountInput(e, key)} />
</Col>
<FormControl.Feedback />
<HelpBlock>{this.state.bankAccounts[key].formErrors.iban}</HelpBlock>
</FormGroup>
<FormGroup controlId={'formHorizontalBankAccount' + key} validationState={this.state.bankAccounts[key].validationState.bankname}>
<Col componentClass={ControlLabel} sm={2}>
Bankname
</Col>
<Col sm={10}>
<FormControl type="text" name={'bankname'+key} key='bankname' value={this.state.bankAccounts[key].bankname} placeholder="Bank name" onChange={(e) => this.handleBankAccountInput(e, key)} />
</Col>
<FormControl.Feedback />
<HelpBlock>{this.state.bankAccounts[key].formErrors.bankname}</HelpBlock>
</FormGroup>
</div>
)
}
This is how I render inputs.
Like this. Bank accounts
{Object.keys(this.state.bankAccounts).map(this.renderBankAccountInput)}
{ this.state.bankAccounts.length < 1 &&
<HelpBlock>You should provide at least one bank account</HelpBlock>
}
<button
onClick={(e) => {
e.preventDefault();
this.addBankAccountInput();
}}
>Add Bank Account</button>`
Would appreciate your help!
It is due to a tricky and headache problem of React. You are using the array index as the key to mapped components by this line <div key={key}>. It makes React confused when updating the array, to which property belong to which component and leads to an unpredictable result.
You can refer to this SO answer with more explanation about the issue in Preact, which is an alternative to React. The explanation can also be applied in React as well.
Solution:
Generate an uuid to your component list. There are my library provides this feature like lodash-uuid or shortid
In your situation, you can use bankAccounts[key][iban] as your component key.

Submit form in classic ASP / VB Script

There is a classic ASP and when Submit button is clicked, it calls Java Script function. The script contains validation of a text box: frmCode and when this validation is passed or the text box is empty, I want to submit form.
However, Set frm = window.document.forms(0) throws an error says "800a01a8|Object_required:_''"
I also tried frm = window.document.forms("form1") but it did not work either.
Any advice would be appreciated. Thank you in advance.
<form Method="post" Action="Test.asp" onSubmit="return OKToSubmit()" id="form1" name="form1" target=_blank>
.....
..... more lines..
.....
<input type="text" id="frmCode" name="frmCode"
style="WIDTH: 248px; HEIGHT: 24px" size=1 maxlength="115">
.....
..... more lines..
.....
<input Type="button" Value="Submit" onClick="OKToSubmit()" id="btnSubmit" name="btnSubmitn">
.....
..... more lines..
.....
<SCRIPT ID=clientEventHandlersVBS type="text/Javascript">
function OKToSubmit(){
var availableCode = new Array();
<%
Dim frm 'reference to form
Set frm = window.document.forms(0)
idx = 0
for idx = 0 to UBound(codeList)-1
%>
availableCode[<%=idx %>] = unescape('<%= Escape(codeList(idx)) %>');
<% next %>
var strCode = document.getElementById('frmCode').value;
var validationFlag = 0;
loopValidation:
for (var i = 0; i < availableCode.length; i++) {
if (strCode == availableCode[i]){
validationFlag = 1;
break loopValidation;
}
}
if (validationFlag == 0 && !(strCode == "")){
alert("Code does not exist. Please check again.");
document.getElementById('frmCode').value = "";
<%
OKToSubmit = False
%>
} else {
<%
OKToSubmit = True
frm.Submit
%>
}
}
</SCRIPT>
see if this gets you what you want:
function OKToSubmit(){
var availableCode = new Array();
var frm = window.document.forms[0];
<%
idx = 0
for idx = 0 to UBound(codeList)-1
%>
availableCode[<%=idx %>] = unescape('<%= Escape(codeList(idx)) %>');
<% next %>
var strCode = document.getElementById('frmCode').value;
var validationFlag = 0;
loopValidation:
for (var i = 0; i < availableCode.length; i++) {
if (strCode == availableCode[i]){
validationFlag = 1;
break loopValidation;
}
}
if (validationFlag == 0 && !(strCode == "")){
alert("Code does not exist. Please check again.");
document.getElementById('frmCode').value = "";
return false;
} else {
frm.submit();
}
}
I moved document.getElementById("form1").submit(); from server side code to client code in Java Script part. Then it is working now. Thank you again for all of your advice.

Image capture/upload with Phonegap (cordova) for iPhone not working

I have been trying to set up an app through PhoneGap (Cordova) to take images and upload them to our server. I have gone through so many of the responses on here and tried the code in them. I can get the camera up and taking a photo, I can access the phone gallery even. But I can not get it to send the image to the server. I've tried sending the image, and even sending the base64 image stream. I can't get it to the server.
Here is the javascript on the client side:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
}
function ImageUpload() {
this.useExistingPhoto = function(e) {
this.capture(Camera.PictureSourceType.SAVEDPHOTOALBUM);
}
this.takePhoto = function(e) {
this.capture(Camera.PictureSourceType.CAMERA);
}
this.capture = function(sourceType) {
navigator.camera.getPicture(this.onCaptureSuccess, this.onCaptureFaile, {
destinationType: Camera.DestinationType.FILE_URI,
soureType: sourceType,
correctOrientation: true
});
}
this.onCaptureSuccess = function(imageURI) {
var fail, ft, options, params, win;
success = function(response) {
alert("Your photo has been uploaded!");
};
fail = function(error) {
alert("An error has occurred: Code = " + error.code + "\nMessage = "+error.message);
};
options = new FailUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "text/plain";
params = {
val1: "some value",
val2: "some other value"
};
options.params = params;
ft= new FileTransfer();
ft.upload(imageURI, 'http://style.appdev01.com/app/client-profile.php', success, faile, options);
}
this.OnCaptureFail = function(message) {
alert("Failed because: "+message);
}
};
var imageuploader = new ImageUpload();
Two buttons call imageuploader.takePhoto and .useExistingPhoto on click.
On the server side I have this php:
if(isset($_FILES['file'])) {
$target_path = "/home/style/public_html/images/client_images/app_image.jpg";
move_uploaded_file($_FILES['file']['tmp_name'], $target_path);
$insert = "INSERT INTO
`fut`
SET
`request` = '".serialize($_POST)."',
`file` = '".serialize($_FILES)."'";
$mysql->query($insert);
}
This is just to store the POST and FILE arrays to the db to make sure they came through and create the image.
But again, nothing is getting to the server. Any help would be GREATLY appreciated. I've tried so many versions of this code from so many questions here and all over the web.
define ('SITE_ROOT', realpath(dirname(__FILE__))); /* echo SITE_ROOT; to dir
move_uploaded_file($_FILES["file"]["tmp_name"],SITE_ROOT."/uploads/".$_FILES["file"]["name"]); // will move file, make sure uplaods has write permission!
That works for me on Android Simulator, not on Tablet, but let me know if you have it working, busy on the same thing.
$myarray = array( $_REQUEST);
foreach ($myarray as $key => $value) {
echo "<p>".$key."</p>";
echo "<p>".$value."</p>";
echo "<hr />";
}
That you can use to check POST / GET!
Try this is my code. It has worked for me.
Encode your URL by encodeURI method
fileKey with "file" as in your server side script $_FILES['file']
uploadFile: function(refNo){
var uri = fileUpload.fileUri;
var file = uri.substr(uri.lastIndexOf('/') + 1);
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = file;
options.mimeType="image/jpeg";
alert("name === "+uri);
options.chunkedMode = false;
var ft = new FileTransfer();
Common.ajaxLoading('show');
ft.upload(uri,encodeURI("http://172.16.1.147:80/upload/home.php") , fileUpload.uploadSuccess, fileUpload.uploadFail, options, true);
},