I want to resume uploading after the internet is connected again
if the internet is cutoff for short time it resumes again but if the time increased ,it wouldn't increase the progress of uploading
my Script :
document.forms["upload-vimeo"].onsubmit = function(e){
e.preventDefault();
let file = this.url.files[0];
let id= "' . $id . '";
let type= this.video_type.value;
let name= this.name.value;
let description= this.description.value;
let formdata = new FormData();
formdata.append("url", file);
formdata.append("id", id);
formdata.append("type", type);
formdata.append("name", name);
formdata.append("description", description);
let http = new XMLHttpRequest();
http.upload.addEventListener("progress", function(event){
let percent = (event.loaded / event.total) * 100;
document.querySelector("progress").value = Math.round(percent);
var element = document.getElementById("value");
element.innerHTML = Math.round(percent)+" %";
});
http.addEventListener("load", function(){
if(this.readyState == 4 && this.status == 200){
if(!this.responseText){
console.log(this.responseText);
window.location.replace("' . $url . '");
}
else{
console.log(this.responseText);
}
}
});
http.open("post", "script.php");
http.send(formdata);
}
My php is normal uploading to vimeo
any ideas to reach that ?
Related
Searched through the Overflow to see if I can spot a solution to this issue, but unfortunately nothing seems to be specific enough.
I'm building an Ionic app with a photo upload feature (using the cordova-filetransfer plugin), and have an API endpoint set up to receive the image. The Ionic JS is able to process the image successfully, but the API responds back with the "disallowed keys" error; only it's full of random garbled nonsense.
The clean_input function:
public function clean_input_keys($str)
{
$chars = PCRE_UNICODE_PROPERTIES ? '\pL' : 'a-zA-Z';
if ( ! preg_match('#^['.$chars.'0-9:_.-]++$#uD', $str))
{
exit('Disallowed key characters in global data: '.$str."\n [GLOBAL vars] \n".Kohana::debug($GLOBALS));
}
return $str;
}
The full response:
Disallowed key characters in global data: '()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖ×ØÙÚâãäåæçèéêòóôõö÷øùúÿÛ
[GLOBAL vars]
<pre>array: </pre>
The uploadImage function from the mobile app:
$scope.uploadImage = function(datetime) {
// Destination URL
var uploadUrl = "url/goes/here";
// File for Upload
var imagePath = $scope.urlForImage($scope.image);
console.log('Path: '+imagePath);
// File name only
var filename = $scope.addZero(datetime.getDate()) + $scope.addZero((datetime.getMonth() + 1)) + datetime.getFullYear() + '-' + $scope.addZero(datetime.getHours()) + $scope.addZero(datetime.getMinutes()) + '-' + $scope.incidentData.store + '-' + $scope.incidentData.location + '.jpg';
filename = filename.replace(/\s+/g, '');
console.log('Filename: '+filename);
var success = function (r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
};
var fail = function (error) {
alert("An error has occurred: Code = " + error.code);
console.log("Upload error source " + error.source);
console.log("Upload error target " + error.target);
};
var options = new FileUploadOptions();
options.fileKey = "image";
options.fileName = filename;
options.chunkedMode = false
//mimeType: "multipart/form-data",
options.mimeType = "image/jpeg";
var params = {};
params.fileName = filename;
options.params = params;
var headers = {
"API-Key": "keygoeshere",
"Content-Type": "application/x-www-form-urlencoded"
};
options.headers = headers;
var ft = new FileTransfer();
ft.upload(imagePath, uploadUrl, success, fail, options);
}
And the API endpoint function:
public function upload_image()
{
$this->authorise();
$file_temp = $_FILES['image']['tmp_name'];
$file_name = $_FILES['image']['name'];
$target_path = 'path/goes/here';
if (move_uploaded_file($file_temp, $target_path.$file_name)) {
Kohana::log('debug', 'File received: '.$_FILES['image']['name']);
Kohana::log_save();
} else {
Kohana::log('debug', 'Photo upload failed');
Kohana::log_save();
}
}
Sorry if this is a bit too much code, but I cannot work out for the life of me where this error is stemming from - any advice?
The issue turned out to be the headers: I was posting a header (Content-Type) that the plugin already sends by default; the two were clashing and causing the error.
Removing this header, leaving only the API-Key, has allowed the image to be sent.
I am having problems uploading a file with CordovaFileTransfer plugin in ionic.
I have sound file that has been recorded and i need help uploading it.
var targetPath = e.nativeURL;
var win = function (r) {
console.log("Code = " + r.responseCode);
console.log("Sent = " + r.bytesSent);
}
var fail = function (error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=filename;
options.mimeType="audio/wav";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(targetPath, "http://example.come/upload.php", win, fail, options);
And my php script looks like this
header('Access-Control-Allow-Origin: *');
print_r($_FILES);
$new_image_name = "audio.wav";
move_uploaded_file($_FILES["file"]["tmp_name"], "/var/www/html/snappycast_uploads/files/".$new_image_name);
Have any idea what I am doing wrong??
i am trying to upload multiple files
i am using ajax
the problem is that sometimes the uploading is not working
and i am not sure about the reload function reloadtabeladeanexos()
after the upload i am doing a query to mysql and show the uploaded files names and urls on a html table
in my pc i am using chrome and works , but some times when i open a new form it fails to upload the first time if i reload mannualy and try again the upload works well
function reloadtabeladeanexos() {
// location.reload();
$.ajax({
url: window.location.href,
headers: {
"Pragma": "no-cache",
"Expires": -1,
"Cache-Control": "no-cache"
}
}).done(function () {
window.location.reload(true);
});
}
function uploadFile(){
var input = document.getElementById("file1");
for (i = 0; i < input.files.length; i++) {
//alert(input.files.length);
var file = _("file1").files[i];
var idc =<?php echo $pid; ?>;
var ponto=16;
var iddoafme=<?php echo $r_id; ?>;
// alert(<?php echo $pid; ?>);
//alert(ponto);
//alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
formdata.append("idc", idc);
formdata.append("ponto", ponto);
formdata.append("iddoafme", iddoafme);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
//ajax.open("POST", "upload.php?idc="+$r_idc+");
ajax.open("POST", "uploadponto16.php");
ajax.send(formdata);
reloadtabeladeanexos();
}
}
function progressHandler(event){
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
reloadtabeladeanexos();
}
function errorHandler(event){
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
_("status").innerHTML = "Upload Aborted";
}
I'm trying to draw points onto a map based on data in a Postgres DB, can anyone tell me why this won't work.. I'm scratching my head trying to figure it out.
I'm pulling data from a Postgres DB using this PHP code, which appears to be working just fine:
<?php
ini_set('memory_limit', '1024M');
// Connecting, selecting database
$dbconn = pg_connect(**MY LOGON DEETS**)
or die('Could not connect: ' . pg_last_error());
$lat1 = $_GET['lat1'];
$lat2 = $_GET['lat2'];
$lng1 = $_GET['lng1'];
$lng2 = $_GET['lng2'];
$pin_points = 'SELECT lat,lng,price,address_string FROM house_price_data_db.main where lat>=$1 and lat<=$2 and lng<=$3 and lng>=$4';
$result_pinpoints_points = pg_query_params($dbconn,$pin_points,array($lat1,$lat2,$lng1,$lng2)) or die('Query failed: ' . pg_last_error());
$pin_points_array = array();
while($r = pg_fetch_assoc($result_pinpoints_points)) {
$pin_points_array[] = $r;
}
header("Content-type: application/json" ); // set the header to json
echo(json_encode(array_values($pin_points_array), JSON_NUMERIC_CHECK)); // this will return json
pg_close($dbconn);
?>
To try and draw points on a map, using the code outlined below. I feel there's an error/issue with my Javascript, but I can't figure it out:
var lat1=55.55;
var lat2=56.05;
var lng1=8.00;
var lng2=8.45;
function setMarkers(){
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var pinpoints = JSON.parse(xmlhttp.responseText);
var marker;
var i=0;
var lat;
var lng;
var price;
var address;
var post_latlng;
var content;
for (i = 0;i<pinpoints.length;i++){
a=pinpoints[i];
lat=parseFloat(a["lat"]);
lng=parseFloat(a["lng"]);
price=parseFloat(a["price"]);
address=String(a["address_string"]);
post_latlng = new google.maps.LatLng(lat,lng);
content = "<b>Price:</b> " + price + '</br>' + "<b>Address:</b> " + address;
var marker = new google.maps.Marker({
map: map,
title: address,
position: post_latlng
});
map.setCenter(marker.getPosition());
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){
return function(){
infowindow.setContent(content);
infowindow.open(map,marker);
};
})(marker,content,infowindow));
}
}
}
xmlhttp.open("GET","pinpoints.php?lat1="+lat1+"&lat2="+lat2+"&lng1="+lng1+"&lng2="+lng2,false);
xmlhttp.send();
}
For some reason it won't work, I expect the function to call the PHP script, return an array and then use this array's contents and the Javscript function to draw markers on a map, that when clicked display some information. When I use Firebug I'm not getting any errors. Any suggestions on how to resolve this are more than welcome.
It turns out my code was working ok, but that the query I was sending to the database to test the function didn't have any returned rows.
I am designing a app in phonegap. I send multiple base64 images to php webservice. Now i need to decode all those base64 images and save them into database.
I am hoping for the best solution. Thank you.
This is my code for assigning base64 values into a hidden input type.
for(i = 0; i< image.length;i++){
$('#table_postad').append('<input type="hidden" value="'+image[i]+'" name="ad_image'+i+'" class="ad_image"/>');
imageArray.push(document.getElementsByClassName("ad_image")[i].value);
}
Following is the code to connect server:
var server = 'http://example.com/webServiceForProject/';
function sendDataToServer(){
alert("access");
var datas = $("#form_description").serialize();//form_description is id for form
console.log(datas);
$.ajax({
type: 'POST',
data: datas,
url: server+'insert.php',
success: function(data){
alert(data);
},
error: function(){
alert('There was an error adding your comment');
}
});
}
this is php code:
<?php
define('UPLOAD_DIR', 'images/');
$adPhotos = array();
$i=0;
while(isset($_POST["ad_image".$i])){
array_push($adPhotos,($_POST["ad_image".$i]));
$i++;
echo($adPhotos[i]);
}
$j = 0;
while(sizeof($adPhotos)){
$adPhotos[$j]= str_replace('data:image/png;base64,', '', $adPhotos[$j]);
$adPhotos[$j]= str_replace(' ', '+', $adPhotos[$j]);
$file[$j] = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file[$j], $data[$j]);
j++;
}
//insert code here.....
?>
Use php's base64_decode to decode the image and save it to your database (e.g. with mysql_query and an INSERT INTO...-statement.
Ram, you don't have to convert images to base64. Please use this code.
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {}
function browseImage() {
navigator.camera.getPicture(uploadPhoto, function(message) {
alert('get picture failed');
},{
quality: 80,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
}
);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "http://example.com/api/upload.php", win, fail, options);
}
function win(r) {
console.log("Response Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
console.log("Error: Code = " = error.code);
}
</script>
<input type="button" onclick= "browseImage()" value="Browse Image" />
//Server: PHP code to upload file
$img_name = $time."jpg";
if(move_uploaded_file($_FILES["file"]["tmp_name"], "folder/".$img_name)){ //upload files in location folder/
//use mysql query to save the filename. (mysql_query("insert into tbl_name(image) values('$img_name')"))
}