I was working with html5 slice and webworker but when it goes to uploadFile function, nothing happened. nothing being upload
<html>
<head>
<title>Upload Files using XMLHttpRequest</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
</head>
<body>
<form id="fileuploader" enctype="multipart/form-data" method="post" action="upload.php">
<label for="fileToUpload">Select Files to Upload</label><br />
<input type="file" name="fileToUpload[]" multiple="" id="fileToUpload" onchange="fileList();"/><br />
<input type="button" onclick="sendRequest();" value="Upload" />
<!-- a place for File Listing -->
<div id="fileList">
</div>
</form>
</body>
</html>
<script type="text/javascript">
function sendRequest() {
var worker = new Worker("fileupload.js");
worker.onmessage = function(e) {
alert(e.data);
}
var file = document.getElementById('fileToUpload');
for(var i = 0; i < file.files.length; i++) {
worker.postMessage(file.files[i]);
}
}
and for the fileupload.js
var file;
var p = true;
function uploadFile(blobFile, fileName, filePart, totalChunks) {
var xhr = new XMLHttpRequest();
xhr.open("POST", "upload.php"+"?"+"file="+fileName + filePart, true);
xhr.onload = function(e) {
};
xhr.send(blobFile);
}
function process() {
var blob = file;
var originalFileName = blob.name;
var filePart = 0
const BYTES_PER_CHUNK = 100 * 1024 * 1024; // 100MB chunk sizes.
var realFileSize = blob.size;
var start = 0;
var end = BYTES_PER_CHUNK;
totalChunks = Math.ceil(realFileSize / BYTES_PER_CHUNK);
while( start < realFileSize ) {
//self.postMessage(start);
//self.postMessage("test");
var chunk = blob.slice(start, end);
uploadFile(chunk, originalFileName, filePart, totalChunks);
filePart++;
start = end;
end = start + BYTES_PER_CHUNK;
}
}
self.onmessage = function(e) {
file = e.data;
/*for (var j = 0; j < e.data.length; j++) {
files.push(e.data[j]);
}*/
if (p) {
process();
}
}
To summarize your code:
if (!blob.webkitSlice && !blob.mozSlice) {
var chunk = blob.mozSlice(start, end);
// or: var chunk = blob.webkitSlice(start, end);
}
This is the line where you get that error from, and it should be obvious that you need to get an exception there.
Sure, for older versions of those browsers you probably should check for the prefixed functions. But if the "feature" detection has not matched, you will need to use the plain function - may it be because those vendors have dropped the prefixes, or the code is executed in some other browser (Opera, IE). See also Browser compatibility: Notes on the slice() implementations at MDN.
So, use this:
var slice = blob.webkitSlice || blob.mozSlice || blob.slice;
var chunk = slice.call(blob, start, end);
Here is a complete working code.
var file = [], p = true;
function upload(blobOrFile) {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/server', false);
xhr.onload = function(e) {
};
xhr.send(blobOrFile);
}
function process() {
for (var j = 0; j <file.length; j++) {
var blob = file[j];
const BYTES_PER_CHUNK = 1024 * 1024;
// 1MB chunk sizes.
const SIZE = blob.size;
var start = 0;
var end = BYTES_PER_CHUNK;
while (start < SIZE) {
if ('mozSlice' in blob) {
var chunk = blob.mozSlice(start, end);
} else {
var chunk = blob.webkitSlice(start, end);
}
upload(chunk);
start = end;
end = start + BYTES_PER_CHUNK;
}
p = ( j = file.length - 1) ? true : false;
self.postMessage(blob.name + " Uploaded Succesfully");
}
}
self.onmessage = function(e) {
for (var j = 0; j < e.data.length; j++)
files.push(e.data[j]);
if (p) {
process()
}
}
Related
Is there any way to set the max file limit.
I already searched google and found this code (this code isnt working):
function addFile() {
clickFirstOnEnter('dlgAddFile');
var dialogButtons = {};
dialogButtons[t('Upload')] = function () {
var maxtotal = RoxyFilemanConf.MAXTOTAL;
var maxfilesize = RoxyFilemanConf.MAXFILESIZE;
var fileoversize = "";
var totalsize = 0;
if (!$('#fileUploads').val())
alert(t('E_SelectFiles'));
else {
if (!RoxyFilemanConf.UPLOAD) {
alert(t('E_ActionDisabled'));
//$('#dlgAddFile').dialog('close');
}
else {
var files = $('#fileUploads')[0].files;
for (var i = 0; i < files.length; i++) {
//alert(files[i].name);
totalsize += files[i].size;
if ((files[i].size / 1024) > maxfilesize) {
fileoversize = files[i].name + '\n';
}
}
if ((totalsize / 1024 / 1024) > maxtotal) {
alert(t('E_MAXSIZE') + ". Set to " + maxsize + "MB.");
}
else if (fileoversize != "") {
alert("Max total upload : "+ maxfilesize +"KB. Oversized files:\n" + fileoversize);
}
else {
document.forms['addfile'].action = RoxyFilemanConf.UPLOAD;
document.forms['addfile'].submit();
}
}
}
};
dialogButtons[t('Cancel')] = function () { $('#dlgAddFile').dialog('close'); };
$('#dlgAddFile').dialog({ title: t('T_AddFile'), modal: true, buttons: dialogButtons });
}
Adding 2 variables to conf.json
MAXTOTAL and MAXFILESIZE.
but this doesnt work at all..
Anyone who got any suggestions/solution for this problem?
As OP has already discovered, this is a configuration setting. For people searching for a solution in .Net, two changes are required in the web.config for IIS 7.0+. Check the link for more complete details.
I added the elements to my root web.config.
<system.web>
<!-- Max int value of 2gb -->
<httpRuntime maxRequestLength="2097151" appRequestQueueLimit="100000" requestLengthDiskThreshold="2097151" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<!-- maxAllowedContentLength, for IIS, in bytes -->
<requestLimits maxAllowedContentLength="104857600" ></requestLimits>
</requestFiltering>
</security>
</system.webServer>
Sause:
How to increase the max upload file size in ASP.NET?
I've also updated the code to work as intended with version 1.4.5. Make sure you apply this to the main.js/main.min.js files.
function addFile() {
clickFirstOnEnter("dlgAddFile");
$("#uploadResult").html("");
clearFileField();
var a = {};
a[t("Upload")] = {
id: "btnUpload",
text: t("Upload"),
disabled: true,
click: function () {
if (!$("#fileUploads").val() && (!uploadFileList || uploadFileList.length == 0)) {
alert(t("E_SelectFiles"))
} else {
if (!RoxyFilemanConf.UPLOAD) {
alert(t("E_ActionDisabled"))
} else {
// start of change
var maxtotal = RoxyFilemanConf.MAXTOTAL;
var maxfilesize = RoxyFilemanConf.MAXFILESIZE;
var fileoversize = "";
var totalsize = 0;
for (var i = 0; i < uploadFileList.length; i++) {
totalsize += uploadFileList[i].size;
if ((uploadFileList[i].size / 1024) > maxfilesize) {
fileoversize = fileoversize + uploadFileList[i].name + '\n';
}
}
if ((totalsize / 1024 / 1024) > maxtotal) {
alert(t('E_MAXSIZE') + ". Set to " + maxsize + "MB.");
} else if (fileoversize != "") {
alert("Max total upload : " + maxfilesize + "KB. Oversized files:\n" + fileoversize);
} else // end of change
if (window.FormData && window.XMLHttpRequest && window.FileList && uploadFileList && uploadFileList.length > 0)
{
for (i = 0; i < uploadFileList.length; i++) {
fileUpload(uploadFileList[i], i)
}
} else {
document.forms.addfile.action = RoxyFilemanConf.UPLOAD;
document.forms.addfile.submit()
}
}
}
}
};
a[t("Cancel")] = function () {
$("#dlgAddFile").dialog("close")
};
$("#dlgAddFile").dialog({
title: t("T_AddFile"),
modal: true,
buttons: a,
width: 400
})
}
(Posted on behalf of the OP).
This is fixed. I found out that the max file is going through the php.ini.
upload_max_filesize=4M
<head>
<script type="text/javascript">
function GetFileInfo () {
var fileInput = document.getElementById ("ctrl");
document.getElementById("Directory").value = fileInput.val;
}
</script>
</head>
<body onload="GetFileInfo ()">
<input type="file" id="ctrl" webkitdirectory directory multiple size="60" onchange="GetFileInfo ()" />
<div id="info" style="margin-top:30px"></div>
<input type="textarea" id="Directory" name="Directory" value="">
</body>
How I can assign select folder name for Directory?
I got it by looping through the files. See var folder in the code below.
files = e.target.files;
var allFiles = new Array();
for (var i = 0, len = files.length; i < len; i++) {
allFiles[i] = new Array();
file = files[i];
extension = file.name.split(".").pop();
var relativePath = file.webkitRelativePath;
var fullPath = file.path;
var folder = relativePath.split("/");
var format = folder[1];
if (format == 'mobile' || format == 'desktop') {
var folderBits = folder[0].split("_");
fileName = "None";
if (fileName) {
fileName = stripSpaces(file.name);
}
if (file.size > 0) {
size = Math.floor(file.size/1024 * 100)/100;
}
var rundates;
var publisher;
var client;
var campaign;
var creative;
var jobnumber;
for (var b = 0, bits = folderBits.length; b < bits; b++) {
switch(b) {
case 0:
rundates = folderBits[b];
break;
case 1:
publisher = folderBits[b];
break;
case 2:
client = folderBits[b];
break;
case 3:
campaign = folderBits[b];
break;
case 4:
creative = folderBits[b];
break;
case 5:
jobnumber = folderBits[b];
break;
default:
}
}
allFiles[i] = {
rundates: rundates,
publisher: publisher,
format: format,
client: client,
campaign: campaign,
creative: creative,
jobnumber: jobnumber,
filename: fileName,
size: size,
};
}
}
Below is my Puzzle image code. I have getting only one image because of onload function so please suggest me to getting more image
this file is include in my main html code but one Image will be displayed and another is display NULL
<html>
<head>
<title>HTML5 Puzzle Game</title>
<script type="text/javascript">
window.onload = onReady;
var can;
var ctx;
var img;
var clickX;
var clickY;
var selected1;
var selected2;
var blockSize = 160;
var piecesArray = new Array();
function onReady()
{
can = document.getElementById('myCanvas');
ctx = can.getContext('2d');
img = new Image();
img.onload = onImage1Load;
img.src = "images/<?php echo $crows['product_image1']; ?>";
}
function onImage1Load()
{
var r;
for(var i = 0; i < 4; i++)
{
for(var j = 0; j < 3; j++)
{
r = new Rectangle(i * blockSize, j * blockSize, i*blockSize + blockSize, j * blockSize + blockSize);
piecesArray.push(r);
}
}
scrambleArray(piecesArray, 30);
drawImage();
}
function Rectangle(left, top, right, bottom)
{
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
this.width = right - left;
this.height = bottom - top;
}
function scrambleArray(ar, times)
{
var count = 0;
var temp;
var index1;
var index2;
while(count < times)
{
index1 = Math.floor(Math.random()*piecesArray.length);
index2 = Math.floor(Math.random()*piecesArray.length);
temp = piecesArray[index1];
piecesArray[index1] = piecesArray[index2];
piecesArray[index2] = temp;
count++;
}
}
function drawImage()
{
var r;
for(var i = 0; i < 4; i++)
{
for(var j = 0; j < 3; j++)
{
r = piecesArray[i*3+j];
ctx.drawImage(img, r.left, r.top, r.width, r.height, i*blockSize, j*blockSize, blockSize, blockSize);
ctx.strokeStyle = "#fff";
}
}
}
function highlightRect(drawX, drawY)
{
ctx.beginPath();
ctx.moveTo(drawX, drawY);
ctx.lineTo(drawX + blockSize, drawY);
ctx.lineTo(drawX + blockSize, drawY + blockSize);
ctx.lineTo(drawX, drawY + blockSize);
ctx.lineTo(drawX, drawY);
ctx.lineWidth = 2;
// set line color
ctx.strokeStyle = "#fff";
ctx.stroke();
}
function swapRects(r1, r2)
{
var index1;
var index2;
var temp = r1;
index1 = piecesArray.indexOf(r1);
index2 = piecesArray.indexOf(r2);
piecesArray[index1] = r2;
piecesArray[index2] = temp;
}
function onCanvasClick(evt)
{
clickX = evt.offsetX;
clickY = evt.offsetY;
var drawX = Math.floor(clickX / blockSize);
var drawY = Math.floor(clickY / blockSize);
var index = drawX * 3 + drawY;
var targetRect = piecesArray[index];
var drawHighlight = true;
drawX *= blockSize;
drawY *= blockSize;
ctx.clearRect(0, 0, 640, 480);
if(selected1 != undefined && selected2 != undefined)
{
selected1 = selected2 = undefined;
}
if(selected1 == undefined)
{
selected1 = targetRect;
}
else
{
selected2 = targetRect;
swapRects(selected1, selected2);
drawHighlight = false;
}
drawImage();
if(drawHighlight)
highlightRect(drawX, drawY);
}
</script>
</head>
<body>
<div style="margin:0 auto; width:640px; height:480px; border: 4px none #cc6699;">
<canvas id="myCanvas" width="640" height="480" onclick="onCanvasClick(event);" style="border:1px dotted #fff;">
</canvas>
</div>
</body>
</html>
A while ago, I created (with much help) a program that uses php and javascript to make some ambient music by randomizing an array of .ogg files. Now I am trying to re-write it with js alone.
The new code immediately below does not work (the .ogg files do play properly when clicked individually, but nothing happens when you press the 'start' button, which is the main feature). (The code below that (containing php) does work.) I've been over the new code several times and I think I've got the 'typos'. I'm pretty sure the problem is in the syntax of the window.setTimeout line, but haven't quite figured out how it should be.
Thanks for any help you can offer!
<!DOCTYPE html>
<html>
<head>
<title>Audio Testing</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function getRandInt (min, max)
{
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function shuffle(o)
{
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
</script>
<script type="text/javascript">
var tonesTotal = 150;
function getDelays(tonesTotal)
{
var return_array = array();
for (var i = 0; i < tonesTotal; i++)
{
var r = getRandInt(0, 600);
var delay = r * 1000;
return_array.push(delay);
}
return return_array;
}
var delays = new Array();
delays = getDelays(tonesTotal);
$(document).ready(function()
{
$("#start").click(function()
{
var base = 'sound';
for(var i = 0; i < tonesTotal; i++)
var id = base + ((i + 1) );
window.setTimeout ("document.getElementById('" + id + "').play()", delays[i]);
});
});
</script>
</head>
<body style="background-color: #999;">
<button id="start">Start</button>
<br><br>
<script>
var tonesTotal = 150;
var samples = new Array("tone0.ogg", "tone2.ogg", "tone4.ogg", "tone6.ogg", "tone7.ogg", "tone9.ogg", "tone11.ogg", "tone12.ogg");
for (var i=1; i <= tonesTotal; i++)
{
shuffle (samples);
var samplepick = samples[0];
document.write ("<audio controls id='sound" + i + "'><source src='" + samplepick + "' type='audio/ogg'></audio>");
}
</script>
</body>
</html>
PREVIOUS CODE:
<!DOCTYPE html>
<html>
<head>
<title>Audio Testing</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<?php
//$randC = rand(1,4);
$C = 150;
function getDelays($C)
{
$return_array = array();
for($i = 0; $i < $C; $i++)
{
$r = rand(0, 600);
$delay = $r * 1000;
array_push($return_array, $delay);
}
return $return_array;
}
echo "<script type=\"text/javascript\">\n";
echo "var delays = new Array();";
$delays = getDelays($C);
for($i = 0; $i < sizeof($delays); $i++)
{
echo "delays[" . $i . "] = " . $delays[$i] . ";\n";
}
echo "
$(document).ready(function()
{
$(\"#start\").click(function()
{
var base = 'sound';
for(i = 0; i < $C; i++)
{
var id = base + ((i + 1) );
window.setTimeout (\"document.getElementById('\" + id + \"').play()\", delays[i]);
}
});
});
</script>
";
?>
<style type="text/css">
</style>
</head>
<body style="background-color: #999;">
<button id="start">Start</button>
<br><br>
<?php
$samples = array("tone0.ogg", "tone2.ogg", "tone4.ogg", "tone6.ogg", "tone7.ogg", "tone9.ogg", "tone11.ogg", "tone12.ogg");
for ($i=1; $i<= $C; $i++) {
shuffle ($samples);
$samplepick = $samples[0];
echo '<audio controls id="sound'.$i.'">
<source src='.$samplepick.' type="audio/ogg">
</audio>';
}
?>
</body>
</html>
When I tested it locally I found a Javascript error in the getDelays() function: First line of code should be:
var return_array = new Array();
I currently have a table that is being populated by a MySQL table, in turn i want to take the data from these cells and use them to create a simulated real time update, i have it working however due to having multiple rows im using for loops in the javascript functions and i believe this is causing the other functions not to run and i cannot figure out a way round it.
Javascript Code:
var seconds = 5;
var divid = "status";
var url = "boo.php";
var timeout;
function refreshdiv(){
// The XMLHttpRequest object
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Your browser does not support AJAX.");
return false;
}
}
}
// Timestamp for preventing IE caching the GET request
fetch_unix_timestamp = function()
{
return parseInt(new Date().getTime().toString().substring(0, 10))
}
var timestamp = fetch_unix_timestamp();
var nocacheurl = url+"?t="+timestamp;
// The code...
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
document.getElementById(divid).innerHTML=xmlHttp.responseText;
setTimeout('refreshdiv()',seconds*1000);
}
}
xmlHttp.open("GET",nocacheurl,true);
xmlHttp.send(null);
}
// Start the refreshing process
var seconds;
window.onload = function startrefresh(){
setTimeout('refreshdiv()',seconds*1000);
}
function runningtime(int) {
if(int == 0) { //if there is data
console.log("int=0 so no data is present, int: " + int);
} else if(int == 1){
var isRunning = new Array();
isRunning[0] = " ";
for (var i=0; i < 3; i++) {
var bool = 'running' + i;
console.log("Running = " + bool);
running = document.getElementById(bool).innerHTML.substring(10,11);
console.log("running: " + running);
if(isRunning[i] == "1") {
var time = 'Time' + i;
a= document.getElementById(time).innerHTML;
console.log("a= " + a);
hour=a.substring(0,2);
min= a.substring(3,5);
sec= a.substring(6,8);
sec==sec++;
if (min<=9) { min="0"+min; }
if (sec<=9) { sec="0"+sec; }
time = (hour + ":" + min + ":" + sec + " ");
if (document.getElementById) { document.getElementById(time).innerHTML = time; }
else if (document.layers) {
document.layers.theTime.document.write(time);
document.layers.theTime.document.close(); }
} else {
//Do nothing
return;
}
}
timeout = setTimeout("runningtime(1)", 1000);
}
}
function experiencehour(exp) {
if(exp == 0) { //if there is dexphourtexphour
console.log("exp=0 so no data is present, exp: " + exp);
} else if(exp == 1){
var isRunning = new Array();
isRunning[0] = " ";
for (var i=0; i < 3; i++) {
var bool = 'running' + i;
console.log("Running = " + bool);
running = document.getElementById(bool).innerHTML.substring(10,11); //checks if bot running
console.log("running: " + running);
if(isRunning[i] == "1") {
var exph = 'Exph' + i;
var expg = 'Exp' + i;
exphour = document.getElementById(exph).innerHTML; //exphour
currexp = document.getElementById(exp).innerHTML; //current gained exp
exphour =parseInt(exphour);
currexp =parseInt(currexp);
console.log("currexp= " + currexp);
console.log("exphour= " + exphour);
expmin = exphour/60;
console.log("expmin= " + expmin);
expsec = Math.round(expmin/60);
console.log("expsec= " + expsec);
newtotalexp = currexp + expsec;
console.log("newtotalexp= " + newtotalexp);
if (document.getElementById) { document.getElementById(exp).innerHTML = newtotalexp; } //writing new exp
else if (document.lexphouryers) {
document.lexphouryers.theTime.document.write(time);
document.lexphouryers.theTime.document.close(); }
} else {
//Do nothing
return;
}
}
timeout = setTimeout("experiencehour(1)", 1000);
}
}
function variable1hour(var1) {
if(var1 == 0) { //if there is dvar1hourtvar1hour
console.log("var1=0 so no data is present, var1: " + var1);
} else if(var1 == 1){
var isRunning = new Array();
isRunning[0] = " ";
for (var i=0; i < 3; i++) {
var bool = 'running' + i;
console.log("Running = " + bool);
isRunning[i] = document.getElementById(bool).innerHTML.substring(10,11); //checks if bot running
console.log("isRunning = " + isRunning[i]);
if(isRunning[i] == "1") {
var varh = 'Varh' + i;
var varg = 'Var' + i;
console.log("Varh = " + varh);
console.log("Var = " + varg);
var1hour = document.getElementById(varh).innerHTML; //var1hour
currvar1 = document.getElementById(varg).innerHTML; //current gained var1
var1hour =parseInt(var1hour);
currvar1 =parseInt(currvar1);
console.log("currvar1= " + currvar1);
console.log("var1hour= " + var1hour);
var1min = var1hour/60;
console.log("var1min= " + var1min);
var1sec = Math.round(var1min/60);
console.log("var1sec= " + var1sec);
newtotalvar = currvar1 + var1sec;
console.log("newtotalvar= " + newtotalvar);
if (document.getElementById) { document.getElementById(varg).innerHTML = newtotalvar; } //writing new var1
else if (document.lvar1houryers) {
document.lvar1houryers.theTime.document.write(time);
document.lvar1houryers.theTime.document.close();
}
} else {
//Do nothing
return;
}
}
timeout = setTimeout("variable1hour(1)", 1000);
}
}
function stopScript() {
console.log("Stopping script");
clearTimeout(timeout);
}
function startScript(i) {
variable1hour(i);
experiencehour(i);
runningtime(i);
}
Any ideas on how i can get around this so i can get all 3 functions running simultaneously.
I have checked console and im not getting any errors that would stop them from running.
You can't have simultaneously in JS. But you can simulate simultaneous a bit in JS.
Take a look at underscore's defer method.
http://underscorejs.org/#defer
It'd work like this:
Take the loop body and wrap it up in a function
Each iteration through the for loop, make a call to the function using defer
That's basically it. Doing that will allow other functions to "interrupt" any given process (function) and thus "share" the execution thread.
A standard JS implementation w/out defer. I'm trying to simulate the closer of defer. The key takeaway here is that, while the calls still execute in the order that they were queued, all get "started" before any one of them completes. In the case of AJAX async requests, the async response should be able to inject itself between any two loop iterations. You can also set data processing by using slight delays
http://jsfiddle.net/t2z9A/
for(var i = 0; i != 5; ++i)
{
(function(index)
{
document.getElementById('id' + index).innerHTML = 'started...';
setTimeout(function()
{
// kill some time
var str = '';
for(var j = 0; j != 10000000; ++j)
str = str + ' ';
document.getElementById('id' + index).innerHTML = 'Function: 1. Index: ' + index + ' - ' + new Date().getTime();
}, index);
})(i);
}
for(var i = 5; i != 10; ++i)
{
(function(index)
{
document.getElementById('id' + index).innerHTML = 'started...';
setTimeout(function()
{
// kill some time
var str = '';
for(var j = 0; j != 1000000; ++j)
str = str + ' ';
document.getElementById('id' + index).innerHTML = 'Function: 2. Index: ' + index+ ' - ' + new Date().getTime();
}, 1);
})(i);
}